I have been looking for a way to easily get bitmaps of segments of images for a while now but never really found anything. I needed this for example in my last Papervision3d example where I wanted to slice an image and use the slices individually as textures on different surfaces. Since I happened to have 14 free hours recently on my flight back from India and had gotten my hands on the airline charger for my macbook (thanks Sam and Pranav), I ended up writing this quick utility class. The class is really easy to use: all you have to do is create an instance of the class passing it the number of rows and columns to cut the image into. Then, calling the getSlice function passing it a row and column index returns the bitmap representing that segment of the image.
var slicer:ImageSlicer= new ImageSlicer(image, 5,6);
var bmp:BitmapData = slicer.getSlice(1,1);
Note that any DisplayObject can be passed to this class, so you could just as easily slice a dynamically drawn Sprite or, in Flex, any UI component and then grab slices of it. This also has a lot of potential for creating interesting transitions or effects.
The class uses the ‘AS3 Data Structures For Game Developersâ€™ package by Michael Baczynski, specifically the Array2 class (and the Collection interface it implements). The package is pretty impressive and something I plan on using a lot more in future projects that require complicated data structures. The Array2 class is fairly simple but really handy for representing 2 dimensional arrays (matrices).
An example of this class can be seen here. Use the first two text input fields to specify the number of rows and columns to slice the image into and the next two to grab any slice in that matrix. (You will have to explicitly click ‘Slice’ and then ‘Show’ separately). The source of the example can be seen here