Chapter 27 Example 3

by actionscriptbible
♥0 | Line 49 | Modified 2010-02-03 04:01:46 | MIT License
play

ActionScript3 source code

/**
 * Copyright actionscriptbible ( http://wonderfl.net/user/actionscriptbible )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/nVlE
 */

package {
  import flash.display.*;
  import flash.events.*;
  import flash.net.URLRequest;
  import flash.system.LoaderContext;
  import flash.text.*;

  public class ch27ex3 extends Sprite {
    protected var bmpData:BitmapData;
    protected var swatch:Swatch;
  
    public function ch27ex3() {
      var l:Loader = new Loader();
      //photo   (CC-BY) Roger Braunstein
      //source  http://www.flickr.com/photos/rogerimp/188712483/
      var url:String = "http://actionscriptbible.com/files/pastels.jpg";
      l.load(new URLRequest(url), new LoaderContext(true));
      l.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
      l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
      addChild(l);
    }
    
    protected function onComplete(event:Event):void {
      var loader:Loader = LoaderInfo(event.target).loader;
      if (loader.content is Bitmap) {
        bmpData = Bitmap(loader.content).bitmapData;
        swatch = new Swatch();
        addChild(swatch);
        addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
      }
    }

    protected function onError(event:ErrorEvent):void {
      trace(event.text);
    }
    
    protected function onMouseMove(event:MouseEvent):void {
      var mx:int = stage.mouseX, my:int = stage.mouseY;
      if (mx >= 0 && mx < bmpData.width && my >= 0 && my < bmpData.height) {
        swatch.x = mx;
        swatch.y = my;
        swatch.color = bmpData.getPixel(mx, my);
        event.updateAfterEvent();
      }
    }
  }
}

import flash.display.Shape;
class Swatch extends Shape {
  public function set color(c:uint):void {
    graphics.beginFill(c);
    graphics.lineStyle(0, 0xffffff, 1, true);
    graphics.drawRect(10, 10, 25, 15);
    graphics.endFill();
  }
}