AS3 - Scale BitmapData

Tom picture Tom · May 23, 2012 · Viewed 17.7k times · Source

I'd like to scale a BitmapData to different sizes such as 200, 400, 600 and 800.

What is a good way to do that?

Answer

OXMO456 picture OXMO456 · May 24, 2012

You can't directly scale a BitmapData but you can make a scaled clone of it. Here is a quick example for scaling a BitmapData :

package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Matrix;

import mx.core.BitmapAsset;

public class Test extends Sprite {


    [Embed(source="test.jpg")]
    private var Image:Class;

    public function Test() {

        var originalBitmapData:BitmapData = BitmapAsset(new Image()).bitmapData;

        function scaleBitmapData(bitmapData:BitmapData, scale:Number):BitmapData {
            scale = Math.abs(scale);
            var width:int = (bitmapData.width * scale) || 1;
            var height:int = (bitmapData.height * scale) || 1;
            var transparent:Boolean = bitmapData.transparent;
            var result:BitmapData = new BitmapData(width, height, transparent);
            var matrix:Matrix = new Matrix();
            matrix.scale(scale, scale);
            result.draw(bitmapData, matrix);
            return result;
        }

        var bitmapA:Bitmap = new Bitmap(originalBitmapData);
        addChild(bitmapA);

        var bitmapB:Bitmap = new Bitmap(scaleBitmapData(originalBitmapData, 0.5));
        addChild(bitmapB);

    }
}
}