CSS sprites with AS3

CSS sprites is a very convenient way to use images. Graphics are placed into one file and CSS defines which part of the image is shown on mouse over and mouse click. One image could hold all graphics used on a website.

Flash has skins for components and the SimpleButton class is quite close to CSS Sprites. I wanted a simpler way to create buttons and use graphics. My IconButton class extends the SimpleButton and slices the given image and sets those slices as upState, overState and downState. HitState is always the upState. IconButton has one extra state: disabled.

MultiIconButton is an extended IconButton. Like its name implies, it has multiple IconButtons. Well, code-wise it has only one, but it has different phases so one image can have multiple different icons for various uses. The illustration below explains the principle.

Scale9IconButton differs from the IconButton in its ability to scale buttons like the scale9 in Flash. See the illustration, example code and download the source and examples.

//get the bitmapdata from the library
var img:BitmapData = new SettingsIcon();

// 27 is the width and 24 the height of the visible area
// image is automagically sliced
_iconButton = new IconButton(img,27,24);
addChild(_iconButton);

//events are added as usual
_iconButton.addEventListener(MouseEvent.CLICK,iconButton_CLICK);

//multiIconButton works exatly the same way
// get the graphics
img = new VolumeIcons();
_multiIconButton = new MultiIconButton(img,27,24);
addChild(_multiIconButton);
_multiIconButton.addEventListener(MouseEvent.CLICK, multiIconButton_CLICK);

//to change the active part, set the "phase"
_multiIconButton.phase = 3

//the constructor of the Scale9Button has 3 parameters more
// first the img, width and height of the slices
//then the new width and height and the scale9 rectangle
// get the graphics
img = new Scale9Button();
_scale9IconButton = new Scale9IconButton(img,144,45,250,45,new Rectangle(50,10,10,10));
addChild(_scale9IconButton);
_scale9IconButton.addEventListener(MouseEvent.CLICK, scale9IconButton_CLICK);

Kommentoi