Previous Page
Next Page

Recipe 8.7. Creating a Flood Fill

Problem

You want to fill a large area, possibly irregular, with a color.

Solution

Use the floodFill( ) method of the BitmapData class.

Discussion

The floodFill( ) method has the same syntax as the setPixel( ) method. That is, you pass it an x, y coordinate and a color. The method colors that pixel and any surrounding pixels the same color. This is the same as the bucket tool in most graphics programs, such as Adobe Photoshop.

The following code demonstrates it in action. It first creates a bitmap and a number of random squares and then sets up a mouseDown handler that performs a flood fill on the selected pixel:

package {
    import flash.display.Sprite;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.events.MouseEvent;
    import flash.geom.Rectangle;

    public class FloodFillDemo extends Sprite {
        private var _bitmap:BitmapData;

        public function FloodFillDemo (  ) {
            var sprite:Sprite = new Sprite(  );
            addChild(sprite);
            _bitmap = new BitmapData(stage.stageWidth,
                                 stage.stageHeight, 
                                 false, 0xffffffff);
    
            for(var i:int = 0; i < 20; i++) {
                _bitmap.fillRect(new Rectangle(
                             Math.random(  ) * stage.stageWidth,
                             Math.random(  ) * stage.stageHeight,
                             50, 50), Math.random(  ) * 0xffffffff);
            }
            var image:Bitmap = new Bitmap(_bitmap);
            sprite.addChild(image);
            sprite.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
        }

        public function onMouseDown(event:MouseEvent):void {
            _bitmap.floodFill(mouseX, mouseY, 0xffff0000);
        }
    }
}

See Also

Recipes 8.5, 8.6, 8.8, 8.9, 8.10, and 8.11 for other ways to add graphical content to a bitmap.


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)