Tag Archives: grid

Cut Image Into Squares

Actionscript:
  1. [SWF(width=650, height=650)]
  2. var loader:Loader = new Loader();
  3. loader.load(new URLRequest("http://actionsnippet.com/wp-content/chair.jpg"));
  4. loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
  5. x = y = 25;
  6. var w:Number;
  7. var h:Number;
  8. var rows:Number = 20;
  9. var cols:Number = 20;
  10. var tiles:Vector.<Sprite> = new Vector.<Sprite>();
  11. function onLoaded(evt:Event):void{
  12.     w = evt.target.width;
  13.     h = evt.target.height;
  14.     var image:BitmapData = Bitmap(evt.target.content).bitmapData;
  15.     var tileWidth:Number = w / cols;
  16.     var tileHeight:Number = h / rows;
  17.     var inc:int = 0;
  18.     var pnt:Point = new Point();
  19.     var rect:Rectangle = new Rectangle(0,0,tileWidth,tileHeight);
  20.     for (var i:int = 0; i<rows; i++){
  21.         for (var j:int = 0; j<cols; j ++){
  22.              var currTile:BitmapData= new BitmapData(tileWidth, tileHeight, true, 0x00000000);
  23.              rect.x = j * tileWidth;
  24.              rect.y = i * tileHeight;
  25.              currTile.copyPixels(image, rect, pnt, null, null, true);
  26.              var bit:Bitmap = new Bitmap(currTile, "auto", false);
  27.              var s:Sprite = tiles[inc] = Sprite(addChild(new Sprite()));
  28.              // offset them a little bit to show that they are in fact tiles.
  29.              s.x = rect.x + Math.random()*10 - 5;
  30.              s.y = rect.y + Math.random()*10 - 5;
  31.              
  32.             /* If you have TweenLite, try something like this:
  33.              s.x = rect.x;
  34.              s.y = rect.y;
  35.              TweenLite.from(s, 0.3, {x:Math.random()*stage.stageWidth, y:Math.random()*stage.stageHeight, alpha:0, delay:inc / 50});
  36.              */
  37.              s.addChild(bit);
  38.              inc++;
  39.         }
  40.     }
  41. }

This snippet shows how to cut a dynamically loaded image up into small squares (or rectangles). Each square is placed into a sprite and these sprites are stored in a vector for later use. This kind of thing could be useful in conjunction with tweening engines to create transition effects. If you have TweenLite on your machine you could add the import statement "import gs.TweenLIte" and uncomment lines 33-35.

For the purposes of this demo I just offset each sprite slightly to show that it the loaded image has in face been cut up. Here are a few stills with created by altering the rows and cols variables:

Without any animation, this snippet is a bit boring - again, using TweenLite or some other tweening engine is the way to go.

Posted in BitmapData, external data | Also tagged , , | 12 Comments