Below is some code that I wrote that will automatically select the best text color based on it’s background. I know the word “best” is subjective, so I really should say it will have the best contrast. This accomplished using color matrices and Quasimondo’s great ColorMatrix class. It basically sets the text color to same as the background, then inverts the color, and finally, desaturates the color. The problem is that it starts to get muddy when you get to a middle tone. To fix this I added a contrast property that when set to 100, always produces either black or white. You can lower this property to see the whole range of grays. In the example below you can click on the color picker to set a new background color. As you move around you should see the text changing. The class code is below as well.
[as]import com.quasimondo.geom.*;
import flash.filters.*;
import flash.geom.*;
class AutoTextColor {
private var backClip:MovieClip;
private var textClip:MovieClip;
private var cm:ColorMatrix;
private var trans:Transform;
private var ct:ColorTransform;
private var contrast:Number;
function AutoTextColor(bc:MovieClip, tc:MovieClip) {
ct = new ColorTransform();
trans = new Transform(bc);
contrast = 100;
backClip = bc;
backClip.cacheAsBitmap = true;
textClip = tc;
textClip.cacheAsBitmap = true;
}
public function setContrastLevel(con:Number):Void {
contrast = con;
}
public function setBackColor(col:Number):Void {
ct.rgb = col;
trans.colorTransform = ct;
cm = new ColorMatrix();
cm.colorize(ct.rgb,1);
cm.invert();
cm.desaturate();
cm.adjustContrast(contrast,contrast,contrast);
textClip.filters = [new ColorMatrixFilter(cm.matrix)];
}
}[/as]
Lee








Sweet! Good work as always Lee.
Yeah Lee, that’s can simplify a lot. Thanks buddy!!
Hey Lee… Nice work!!
I found some spots that resulted in a grey text and low contrast (see screenshot).. I guess something went wrong somewhere.. But this looks great
http://www.farb.nl/stuff/colorpicker.jpg
Thanks Bas! I actually should just check if it is close to black or white, then just make it black or white.
Curious if there’s a way for flash to automatically pick 5 random colors from some bit map so I can dynamically manipulate some shapes based on those 5 colors?
this is fantastic.
I have been trying to incorporate this text contrast functionality into your latest GOTOANDLEARN Reading color pixels tutorial. I am not having much luck. Any chance of getting the source files for this?
Lee,
U did a good job……..
……keep it up.
Hi, this is great,maybe a dumm question, but
How do I combinde this with a msql table, i wont to store the color code that has been chosen, How do go about this,
thank you….
After a few hours of toying around with this I realized that to use the class as is, the initial text color has to be white. If you want to start off with a dark text color you can add the line cm.invert(); before cm.colorize(ct.rgb,1); in the setBackColor function. This will invert the dark text to light.