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]