Wednesday, September 17, 2008

Fun With Colors

I’m in the middle of a deep review of some curriculum for developing web pages. (This curriculum was talked about in a previous post.) It’s really good stuff and I think a lot of teachers will find it valuable. During the course of this review I came upon the discussion of colors and how they are represented in web pages. Colors are defined using a mix of red, green and blue specified as a hexadecimal number. These values go from 0 to ff (or 0 to 255 for you decimal people.)

There are lots of tools on the web and elsewhere that let people pick colors and then supply the hex value they need of course. If you work with web pages on a regular basis you probably even have a favorite. But as a programming geek I decided it would be fun to write my own. Yes, there are people for whom writing a little code while everyone else is watching TV is our idea of fun and relaxing. So I came up with this:


I like sliders. :-) The user moves the sliders to get the color they want (the code sets the background of a picture box in this case) and the hex value is placed in a text box. I used a text box because it is easy to do a copy and paste from text boxes. The key code looks like:

ColorBox.BackColor =  Color.FromArgb( iRed,iGreen,iBlue);
txtHex.Text = iRed.ToString("X2")  + iGreen.ToString("X2")  + iBlue.ToString("X2");

Yes, that is in C# just to remind Clint that I do use it now and again. Interestingly enough when I made my Visual Basic .NET version I was able to copy/paste much of the code from the C# into the VB. Or course I had to delete all those semi-colons afterwards. In any case it is very nice that the ToString method lets the programmer request that integers be displayed as hexadecimal values. I was toying with the idea of writing a function to do that but a) I like the idea of using built in facilities and b) that is something I might leave for students in an assignment just because I am evil. :-)

A little side trick that shows the amazing coolness of Visual Studio and .NET, I opened up two copies of Visual Studio with the C# project in one of them. In the second I created a new Visual Basic Windows application project. Then I did a copy of all the objects on the form in the C# project and pasted them into the form of the VB project. Then I just added code. Again some copy paste, removed the semi-colons but with different syntax and stuff for specifying form level variables and functions/sub routines. I also did not have to explicitly initialize the form level variables because Visual Basic does that on its own. I’ll probably do it to make the program more self documenting though. That’s just good practice.

Hum, I wonder if I should set the color of the words above the slider based only on the value of that particular slider? Not sure how that would look. Left as an exercise for the reader perhaps?

No comments: