Create a gist now

Instantly share code, notes, and snippets.

package com.illuzor.tools {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.system.System;
import flash.utils.Dictionary;
/**
* @author illuzor
*/
public class ImageAtlas {
private var rectangles:Dictionary = new Dictionary();
private var bitmapDatas:Dictionary = new Dictionary();
private var imageData:BitmapData;
public function ImageAtlas(imageData:BitmapData, xmlData:XML) {
this.imageData = imageData;
for each (var subTexture:XML in xmlData.SubTexture) {
var name:String = subTexture.attribute("name");
var x:Number = parseFloat(subTexture.attribute("x"));
var y:Number = parseFloat(subTexture.attribute("y"));
var width:Number = parseFloat(subTexture.attribute("width"));
var height:Number = parseFloat(subTexture.attribute("height"));
rectangles[name] = new Rectangle(x, y, width, height);
}
System.disposeXML(xmlData);
}
public function getBitmapData(name:String):BitmapData {
if (!bitmapDatas.hasOwnProperty(name)) {
var rect:Rectangle = rectangles[name];
var bitmapData:BitmapData = new BitmapData(rect.width, rect.height);
bitmapData.copyPixels(imageData, rect, new Point());
bitmapDatas[name] = bitmapData;
}
return bitmapDatas[name];
}
public function getBitmap(name:String):Bitmap {
var bitmap:Bitmap = new Bitmap(getBitmapData(name));
bitmap.smoothing = true;
return bitmap;
}
public function getSprite(name:String):Sprite {
var sprite:Sprite = new Sprite();
sprite.addChild(getBitmap(name));
return sprite;
}
public function getShape(name:String):Shape {
var bdata:BitmapData = getBitmapData(name);
var shape:Shape = new Shape();
shape.graphics.beginBitmapFill(bdata);
shape.graphics.drawRect(0, 0, bdata.width, bdata.height);
shape.graphics.endFill();
return shape;
}
public function dispose():void {
for each (var bitmapData:BitmapData in bitmapDatas) {
bitmapData.dispose();
}
imageData.dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment