How to put an image (say, PNG) on a graphics in Flex 3?
Solution 1
Off the top of my head I can think of two things that might help you (depending on what it is exactly that you're trying to achieve):
If you just want to display an image you've embedded, you can add an Image component to the stage and set the value of its source
as the graphical asset (Class
) that you're embedding:
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;
myImage.source = MyGfx;
If you actually want to draw a bitmap onto a Graphics
object, you can do this with the beginBitmapFill() method:
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;
var myBitmap:BitmapData = new MyGfx().bitmapData;
myGraphics.beginBitmapFill(myBitmap);
myGraphics.endFill();
You might find the Flex Quick Starts articles on Adobe's site useful, especially the "Embedding Assets" section.
Solution 2
The accepted answer is incomplete because without a call to drawRect()
nothing will be drawn. I have implemented it this way and it works. Notice that I added a matrix translation, otherwise images would have to be drawn either at 0,0 or would be clipped incorrectly.
[Embed(source='assets/land-field.png')]
private var ImgField:Class;
private var field:BitmapData = new ImgField().bitmapData;
public static function drawImage(g:Graphics, image:BitmapData, x:int, y:int):void {
var mtx:Matrix = new Matrix();
mtx.translate(x, y);
g.beginBitmapFill(image, mtx, false, false);
g.drawRect(x, y, image.width, image.height);
g.endFill();
}
Comments
-
Fixpoint about 2 years
I'm new to Flex, and I'm trying to write a simple application. I have a file with an image and I want to display this image on a Graphics. How do I do this? I tried [Embed]-ding it and adding as a child to the component owning the Graphics', but I'm getting a "Type Coercion failed: cannot convert ... to mx.core.IUIComponent" error.
-
ncases over 15 yearsCan you post some sample code to show how you're intending to use a Graphics object, please?
-
-
user772401 over 15 yearsThis is somewhat relevant here too: stackoverflow.com/questions/554631/…
-
android927 over 9 yearsBut this only works if your using flash. Since he did not specify that he was using flash, we should assume that he is working in pure actionscript.