Applies to VB4+ |
A color value in Windows is a long integer that packs the red, green, and blue components in the format &H00bbggrr
, where each component can range from &H00
to &HFF
(decimal 255). The functions below extract each component:
These functions use the And operator to mask out unwanted components; the latter two then use integer division to move the values to the low-order byte.
To combine the three components back into a single color value, use the RGB function provided by Visual Basic. Alternatively, use this formula:
Dim Color As Long Color = Red Or (Green * &H100&) Or (Blue * &H10000)
If you need to loop through and manipulate a large number of color values, don't use the GetRed, GetGreen, GetBlue, or RGB functions. Calling a procedure to do something is always a bit slower than simply doing it. If you call a procedure many times, these bits add up and cause your program to slow down noticeably.
For example, suppose you have an array of pixels and you want to lighten the color of every pixel. To do this, you can average each color with white:
Dim Color As Long, Red As Byte, Green As Byte, Blue As Byte For Index = 1 To NumPixels Color = Pixels(Index) Red = (GetRed(Color) + 256) \ 2 Green = (GetGreen(Color) + 256) \ 2 Blue = (GetBlue(Color) + 256) \ 2 Pixels(Index) = RGB(Red, Green, Blue) Next Index
This is the naïve way to code the loop. You can cut the execution time in half by replacing each function call with the body of the function:
Dim Color As Long, Red As Byte, Green As Byte, Blue As Byte For Index = 1 To NumPixels Color = Pixels(Index) Red = ((Color And &HFF&) + 256) \ 2 Green = ((Color And &HFF00&) \ &H100& + 256) \ 2 Blue = ((Color And &HFF0000) \ &H10000 + 256) \ 2 Pixels(Index) = Red Or (Green * &H100&) Or (Blue * &H10000) Next Index
When compiled to native code with optimizations enabled, the loop runs five times faster!
For this particular example, you can do even better. With some mathematical trickery, you can cut the execution time in half yet again:
For Index = 1 To NumPixels Pixels(Index) = ((Pixels(Index) Or &H10101) + &HFFFFFF) \ 2 Next Index
Remember: You can improve performance, sometimes significantly, by eliminating function calls and tweaking your algorithms.
Copyright © 2001 Rising Productions. Last update: November 9, 2001