package
{
import flash.display.BlendMode;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.text.engine.ElementFormat;
import flash.text.engine.TextBlock;
import flash.text.engine.TextElement;
import flash.text.engine.TextLine;
/**
* ...
* @author wvxvw
*/
public class Main extends Sprite
{
private var _textLine:TextLine;
private var _text:String =
<![CDATA[This is text that has KEYWORDS.
I would like to highlight these KEYWORDS by changing their font color
and adding a light yellow background graphic.
]]>.toString().replace(/[\r\n\t]+/g, "");
public function Main()
{
super();
if (super.stage) this.init();
else super.addEventListener(Event.ADDED_TO_STAGE, this.init);
}
private function init(event:Event = null):void
{
var normalFormat:ElementFormat = new ElementFormat(null, 12, 0x000000);
var highlightFormat:ElementFormat = new ElementFormat(null, 14, 0xff0000);
var re:RegExp = /KEYWORDS/g;
var start:int;
var end:int;
var bounds:Rectangle = new Rectangle();
var startBounds:Rectangle;
var endBounds:Rectangle;
var textBlock:TextBlock =
new TextBlock(new TextElement(this._text, normalFormat));
super.removeEventListener(Event.ADDED_TO_STAGE, this.init);
this._textLine = textBlock.createTextLine();
//trace(this._textLine.dump());
bounds.height = this._textLine.height;
bounds.y = this._textLine.height * -1;
while (re.exec(this._text))
{
start = re.lastIndex - 8;
end = start + 8;
startBounds = this._textLine.getAtomBounds(start);
endBounds = this._textLine.getAtomBounds(end);
bounds.left = startBounds.left;
bounds.right = endBounds.right;
trace(bounds);
this._textLine.addChild(this.createMarkerShape(bounds, 0xFFFF00));
}
this._textLine.y = 100;
super.addChild(this._textLine);
}
private function createMarkerShape(rect:Rectangle, color:uint):Shape
{
var s:Shape = new Shape();
var g:Graphics = s.graphics;
g.beginFill(color);
g.drawRect(rect.x, rect.y, rect.width, rect.height);
g.endFill();
s.blendMode = BlendMode.DARKEN;
return s;
}
}
}
Something to get you started...