Avg. Rating 4.5

Problem

Add some text to Graphics() class instance.

Solution

Add needed text to UITextField() instance, take a BitmapData snapshot from it and use this data as specified region fill.

Detailed explanation

Let's imagine a situation when we need to add some text into Graphics() instance - there is no standard mechanism to do this and we are forced to trick. We can't add text but we can add some graphic primitive (such as a rectangle or circle) files with any BitmapData. So, the only thing we actually should to do - create a BitmapData with text-image containing.

Another important thing we should note is proper coordinate shift. In the given example we have some renderer for mesh edge (graphical connection between 2 mesh nodes) which would redraw dynamically. We need to add text with edge property in Graphics instance and be sure it would be added correctly each time enge would be redrawed.

So, we have:

g:Graphics - instance where we should add all adge visualization.

fromX:int, fromY:int, toX:int, toY:int - 2 nodes should be cinnected coordinates;

weight: Number - edge property we should show;

Example code will look like:

g.lineStyle(Number(weight),0x666666);
g.moveTo(fromX,fromY);
g.lineTo(toX,toY);
var uit:UITextField = new UITextField();
uit.text = weight;
uit.autoSize =   TextFieldAutoSize.LEFT;
var textBitmapData:BitmapData =
ImageSnapshot.captureBitmapData(uit);
var sizeMatrix:Matrix = new Matrix();
var coef:Number =
Math.min(uit.measuredWidth/textBitmapData.width,uit.measuredHeight/textBitmapData.height);
sizeMatrix.a = coef;
sizeMatrix.d = coef;
textBitmapData = ImageSnapshot.captureBitmapData(uit,sizeMatrix);
g.lineStyle(0,0,0);
var sm:Matrix = new Matrix();
sm.tx = (fromX+toX)/2;
sm.ty = (fromY+toY)/2;
g.beginBitmapFill(textBitmapData,sm,false);
g.drawRect((fromX+toX)/2,(fromY+toY)/2,uit.measuredWidth,uit.measuredHeight);
g.endFill();

As you can see we added UITextField() instance, took a snapshot via mx.graphics.ImageSnapshot() class method captureBitmapData(). Then we measured it's actual dimmentions and re-captured the text snapshot with proper sizes. Then we set line style to (0,0,0) to hide the rectangle border we don't need. We are going to place out text-image in our g at coordinates (fromX+toX)/2, (fromY+toY)/2). The next important step is to create a replacement Matrix() which we will use to fill rectangle. Without this matrix rectangle filling would be started in g coordinates (0,0) and we would see a situation like below in following screenshot:
 

So, we added Matrix() with tx and ty coefficients set to point we are going to add rectangle. Last step is to add a rectangle and fill it with «text-image» BitmapData using replacement matrix. When the user moves the mesh nodes, the edge would be redrawn, sm.tx and sm.ty would be recounted and rectangle would be filled properly.

Report abuse

Related recipes