Neat little code snippet

| | Comments (4)

Since we were just talking about colors yesterday....

Ever needed to get a random color for debugging purposes? I have! Whenever I start debugging slow drawing code, the first thing I want to know is how often is something being refreshed. Oftentimes, you can speed up your drawing code by simply drawing less! However, knowing when the Paint event is being called can be tricky. Unless you're remote debugging, it's basically impossible to debug using the debugger. So what I do instead is draw a patch with a random color. Every time the patch changes colors, I know I've done a refresh. If I see that thing changing colors like mad, I know that I can optimize by simply removing a lot of refreshes or only refresh parts of the screen.

So here's my handy little code snippet.[rbcode]
Function RandomColor() as Color
return HSV( rnd, rnd, rnd )
End Function[/rbcode]
Yeah, it's just that easy. Remember, HSV takes a level which is [0,1] -- handily enough, that's the same as what rnd returns. So I just use that code and it'll essentially return to me a new color every time it's called.

4 Comments

Calculations dealing with HSV or extracting a color's Hue, Saturation or Value parts is pretty expensive (several floating point ops per part). Take a look at the Wikapedia entry for HSV, and the formula for Hue:

http://en.wikipedia.org/wiki/HSV_color_space

On the other hand, CMY calculations (at least with REALbasic) are very straight forward and would have the same results. For example CMY(0.0, 1.0, 1.0) would equal the RGB: FF0000 (red). The most basic calculations (excluding profiles, ink density and Black channel adjustments) for CMY are:

Red Channel = (1.0 - Cyan) * 255
Green Channel = (1.0 - Magenta) * 255
Blue Channel = (1.0 - Yellow) * 255

Since in this case it doesn't matter if you use HSV or CMY for a random color, try using CMY instead for a slight speed boost.

Interesting factoid! I wasn't going for efficient (I've only ever used it for debugginer purposes really), but that's neat to know.

On Mac OS X, you can use Quartz Debug for the same purpose; it will flash screen updates in yellow, so you can catch spurious redraws in all areas.

For example, you can see why the RB IDE is so slow: panes are redrawn several times. I wouldn't envy the person who had to track down all that redrawing, though--graphics optimization is my least favorite work.

Personally I use HSV( rnd , .5, .5 ) for random color debugging it's just slightly more efficient and not as jarring I think.

Leave a comment

Disclaimer

I'm currently an employee of REAL Software. My blog is mine. The opinions represented in this blog are mine as well and may not represent my employer's opinions. All original material is copyrighted and property of the author.

REALbasic® is a registered trademark of REAL Software, Inc. REAL SQL Server™ and Lingua™ are pending trademarks of REAL Software, Inc. All rights reserved.