Actionscript 3: Slice a Bitmap into tiles

2019-04-16 01:15发布

问题:

I have the Bitmap data from a Loader object and I would like to slice it up into 32x32 squares to use as tiles. What is the most efficient way to do so?

回答1:

I have done the work for you. The basic idea is to use the BitmapData function copyPixels, see Adobe Reference for the same . It lets you copy pixels from one region(specified by a Rectangle) in the source BitmapData, to a specific Point in the destination BitmapData. I have created a new BitmapData for each 32x32 square and looped through the loaded object to populate the squares with copyPixels.

var imageLoader:Loader;

function loadImage(url:String):void
{
    // Set properties on my Loader object
    imageLoader = new Loader();
    imageLoader.load(new URLRequest(url));
    imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
    imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
}
loadImage("Cow Boy.jpg");//--------->Replace this by your image. I hope you know to specify path. 
function imageLoaded(e:Event):void
{
    // Load Image
    imageArea.addChild(imageLoader);

    var mainImage:BitmapData = new BitmapData(imageArea.width,imageArea.height);
    var tileX:Number = 36; 
    var tileY:Number = 36;
    var bitmapArray:Array;

    var tilesH:uint = Math.ceil(mainImage.width / tileX); // Number  of Columns
    var tilesV:uint = Math.ceil(mainImage.height / tileY);// Number of Rows

    mainImage.draw(imageArea);
    imageArea.x += 500;

    bitmapArray = new Array();

    for (var i:Number = 0; i < tilesH; i++)
    {
        bitmapArray[i] = new Array();
        for (var n:Number = 0; n < tilesV; n++)
        {
            var tempData:BitmapData=new BitmapData(tileX,tileY);
            var tempRect = new Rectangle((tileX * i),(tileY * n),tileX,tileY);
            tempData.copyPixels(mainImage,tempRect,new Point(0,0));
            bitmapArray[i][n]=tempData;
        }
    }

    for (var j:uint =0; j<bitmapArray.length; j++)
    {

        for (var k:uint=0; k<bitmapArray[j].length; k++)
        {

            var bitmap:Bitmap=new Bitmap(bitmapArray[j][k]);
            this.addChild(bitmap);
            bitmap.x = (j+1)* bitmap.width + j*10;
            bitmap.y = (k+1)* bitmap.height + k*10;

        }
    }



}
function imageLoading(e:ProgressEvent):void
{
    // Use it to get current download progress
    // Hint: You could tie the values to a preloader :)
}


回答2:

You can use the BitmapData function copyPixels, see this link. It lets you copy pixels from one region(specified by a Rectangle) in the source BitmapData, to a specific Point in the destination BitmapData. Basically you could just create a new BitmapData for each 32x32 square and loop through the loaded object to populate the squares with copyPixels.