Draw text on shape in ActionScript 3

GhassanPL picture GhassanPL · Feb 26, 2010 · Viewed 8.8k times · Source

Is there any way to draw text in a DisplayObject or Shape using only ActionScript? The only way I can find on the web is by creating a TextField, but I can't add a TF to a DisplayObject or Shape.

Edit:

Solved thanks to viatropos.

For anyone that's interested:

DisplayObject implements IBitmapDrawable which can be passed as an argument to the draw function of a BitmapData object, which then can be drawn using graphics.beginBitmapFill.

var textfield:TextField = new TextField;
textfield.text = "text";

var bitmapdata:BitmapData = new BitmapData(theWidth, theHeight, true, 0x00000000);
bitmapdata.draw(textfield);

graphics.beginBitmapFill(bitmapdata);
graphics.drawRect(0, 0, theWidth, theHeight);
graphics.endFill();

Answer

Lance Pollard picture Lance Pollard · Feb 26, 2010

Good question. This is beyond anything I've ever needed to do, but I think I know how to do it.

Shape extends DisplayObject, but not DisplayObjectContainer, so you can't add anything to it. But it does have the graphics property, so you can draw things into it. The best way I can think of is to take a Bitmap snapshot of the TextField, and draw that into the Shape. I know this is what Degrafa does for their RasterText (check out the source, it's really helpful).

If you changed your Shape to a Sprite instead, it's a lot easier. Sprite extends DisplayObjectContainer, so you could add your TextField there.

Hope that helps, Lance