Search code examples
actionscript-3bitmapflashdevelop

Generate a sprite from bitmap in AS3


I am very new to Flex and Action Script 3. I am trying to write a simple function that will copy a rectangular area from a loaded bitmap, and generate a sprite for it. I just want to learn how to copy part of an image to another.

The function is :

public static function GenerateSprite(x:int,y:int,w:int,h:int)
{
var bt:BitmapData = new BitmapData(w, h);
var mtx:Matrix = new Matrix();
mtx.translate(-x, -y);
bt.draw(bitmap, mtx, null, null, null, null);
var s:Sprite = new Sprite();
s.graphics.beginBitmapFill(bt, null, false, false);
s.graphics.endFill;
return s;
}

x,y,w, and h represent the x,y location of the sprite, its width and height respectively.

Any advice is highly appreciated.

yours sincerely

PS: I am using FlashDevelop for this.


Solution

  • You can use copyPixels here, and you need a parameter bitmap for the source bitmap, and a function return value Sprite.

    Here is my fix for you:

    public static function GenerateSprite(bitmap:Bitmap,x:int,y:int,w:int,h:int):Sprite
    {
        var bt:BitmapData = new BitmapData( w, h );
        bt.copyPixels( bitmap.bitmapData, new Rectangle(x,y,w,h), new Point(0,0) );
        var s:Sprite = new Sprite();
        s.graphics.beginBitmapFill( bt, null, false, true );
        s.graphics.drawRect( 0, 0, w, h );
        s.graphics.endFill();
        return s;
    }