0

How do I extract the width and height of an embedded image in AS3 instead of explicitly stating the dimensions? Here's what I'm trying to do:

    [Embed(source="../../lib/spaceship.png")]
    private var ShipImage:Class;
    private var ship_image:BitmapData;

    public function Ship(x:int, y:int, width:Number, height:Number) 
    {
        super(x, y, 36, 64);
        ship_image = new ShipImage().bitmapData;
        speed = new Point(0, 0);
    }

Since super should be called before everything else within the constructor how do I learn about the dimensions beforehand? I'm using FlashDevelop as my IDE.

dragonx99
  • 33
  • 3

2 Answers2

1

You can read those properties through BitmapData#rect:

public function Ship(x:int, y:int, width:Number, height:Number) 
{
    // Would be better if you haven't to pass width and height
    super(x, y, 0, 0);

    // Get the bitmap data
    ship_image = new ShipImage().bitmapData;

    // Set width and height
    width  = ship_image.rect.width;
    height = ship_image.rect.height;

    // ...
}

Other solution with statics:

[Embed(source="../../lib/spaceship.png")]
private static const ShipImage:Class;

private static var spriteWidth:int;
private static var spriteHeight:int;

private static function calculateSpriteSize():void
{
    // Get the sprite "rectangle"
    var rect:Rectangle = new ShipImage().bitmapData.rect;

    // Set width and height
    spriteWidth  = ship_image.rect.width;
    spriteHeight = ship_image.rect.height;
}

// Call the method into the class body
// (yes you can do that!)
calculateSpriteSize();

public function Ship(x:int, y:int, width:Number, height:Number) 
{
    // Retrieve the sprite size
    super(x, y, spriteWidth, spriteHeight);

    // ...
}
Florent
  • 12,310
  • 10
  • 49
  • 58
0

you can extract/resize Image With Scaling. you can re-size image with same aspect ratio or different aspect ratio. if you do not want to re-size then scaleX && scaleY has value 1.0 , if you want to re-size with half of the original size then both factor has value of 0.5 If you want to rotate image Then use Translation.

var matrix:Matrix = new Matrix();
matrix.scale(scalex, scaley);
matrix.translate(translatex, translatey);

var resizableImage:BitmapData = new BitmapData(size, size, true);
resizableImage.draw(data, matrix, null, null, null, true);

this resizableimage returns bitmapdata.

May This Works for You!

JK Patel
  • 858
  • 8
  • 22