/** * VERSION: 0.23 * DATE: 2011-08-30 * AS3 * UPDATES AND DOCS AT: http://www.greensock.com **/ package com.greensock { import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Transform; /** * A BlitMask is basically a rectangular Sprite that acts as a high-performance mask for a DisplayObject * by caching a bitmap version of it and blitting only the pixels that should be visible at any given time, * although its bitmapMode can be turned off to restore interactivity in the DisplayObject * whenever you want. When scrolling very large images or text blocks, a BlitMask can greatly improve * performance, especially on mobile devices that have weaker processors.

* * Here are some of the conveniences BlitMask offers:
* * * @example Example AS3 code: import com.greensock.~~; //create a 200x200 BlitMask positioned at x:20, y:50 to mask our "mc" object and turn smoothing on: var blitMask:BlitMask = new BlitMask(mc, 20, 50, 200, 200, true); //position mc at the top left of the BlitMask using the scrollX and scrollY properties blitMask.scrollX = 0; blitMask.scrollY = 0; //tween the scrollY to make mc scroll to the bottom over the course of 3 seconds and then turn off bitmapMode so that mc becomes interactive: TweenLite.to(blitMask, 3, {scrollY:1, onComplete:blitMask.disableBitmapMode}); //or simply position mc manually and then call update() to sync the display: mc.x = 350; blitMask.update(); * * Notes: *

* * Copyright 2011, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class BlitMask extends Sprite { /** @private **/ public static var version:Number = 0.22; // In order to conserve memory and improve performance, we create a few instances of Rectangles, Sprites, Points, Matrices, and Arrays and reuse them rather than creating new instances over and over. /** @private **/ protected static var _tempContainer:Sprite = new Sprite(); /** @private **/ protected static var _sliceRect:Rectangle = new Rectangle(); /** @private **/ protected static var _drawRect:Rectangle = new Rectangle(); /** @private **/ protected static var _destPoint:Point = new Point(); /** @private **/ protected static var _tempMatrix:Matrix = new Matrix(); /** @private **/ protected static var _emptyArray:Array = []; /** @private **/ protected static var _colorTransform:ColorTransform = new ColorTransform(); /** @private **/ protected static var _mouseEvents:Array = [MouseEvent.CLICK, MouseEvent.DOUBLE_CLICK, MouseEvent.MOUSE_DOWN, MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_OUT, MouseEvent.MOUSE_OVER, MouseEvent.MOUSE_UP, MouseEvent.MOUSE_WHEEL, MouseEvent.ROLL_OUT, MouseEvent.ROLL_OVER]; /** @private **/ protected var _target:DisplayObject; /** @private **/ protected var _fillColor:uint; /** @private **/ protected var _smoothing:Boolean; /** @private **/ protected var _width:Number; /** @private **/ protected var _height:Number; /** @private **/ protected var _bd:BitmapData; /** @private maximum number of pixels (minus one) that each BitmapData cell in the grid can be **/ protected var _gridSize:int = 2879; /** @private **/ protected var _grid:Array; /** @private **/ protected var _bounds:Rectangle; /** @private **/ protected var _clipRect:Rectangle; /** @private **/ protected var _bitmapMode:Boolean; /** @private **/ protected var _rows:int; /** @private **/ protected var _columns:int; /** @private **/ protected var _scaleX:Number; /** @private **/ protected var _scaleY:Number; /** @private **/ protected var _prevMatrix:Matrix; /** @private **/ protected var _transform:Transform; /** @private **/ protected var _prevRotation:Number; /** @private **/ protected var _autoUpdate:Boolean; /** * Constructor * * @param target The DisplayObject that will be masked by the BlitMask * @param x x coorinate of the upper left corner of the BlitMask. If smoothing is false, the x coordinate will be rounded to the closest integer. * @param y y coordinate of the upper right corner of the BlitMask * @param width width of the BlitMask (in pixels) * @param height height of the BlitMask (in pixels) * @param smoothing If false (the default), the bitmap (and the BlitMask's x/y coordinates) will be rendered only on whole pixels which is faster in terms of processing. However, for the best quality and smoothest animation, set smoothing to true. * @param autoUpdate If true, the BlitMask will automatically watch the target to see if its position/scale/rotation has changed on each frame (while bitmapMode is true) and if so, it will update() to make sure the BlitMask always stays synced with the target. This is the easiest way to use BlitMask but it is slightly less efficient than manually calling update() whenever you need to. Keep in mind that if you're tweening with TweenLite or TweenMax, you can simply set its onUpdate to the BlitMask's update() method to keep things synced. Like onUpdate:myBlitMask.update. * @param fillColor The ARGB hexadecimal color that should fill the empty areas of the BlitMask. By default, it is transparent (0x00000000). If you wanted a red color, for example, it would be 0xFFFF0000. */ public function BlitMask(target:DisplayObject, x:Number=0, y:Number=0, width:Number=100, height:Number=100, smoothing:Boolean=false, autoUpdate:Boolean=false, fillColor:uint=0x00000000) { super(); _width = width; _height = height; _scaleX = _scaleY = 1; _smoothing = smoothing; _fillColor = fillColor; _autoUpdate = autoUpdate; _grid = []; if (_smoothing) { super.x = x; super.y = y; } else { super.x = (x < 0) ? (x - 0.5) >> 0 : (x + 0.5) >> 0; super.y = (y < 0) ? (y - 0.5) >> 0 : (y + 0.5) >> 0; } _clipRect = new Rectangle(0, 0, _gridSize + 1, _gridSize + 1); _bd = new BitmapData(width + 1, height + 1, true, _fillColor); this.target = target; this.bitmapMode = true; } /** @private **/ protected function _captureTargetBitmap():void { _disposeGrid(); //capturing when the target is masked (or has a scrollRect) can cause problems. var prevMask:DisplayObject = _target.mask; if (prevMask != null) { _target.mask = null; } var prevScrollRect:Rectangle = _target.scrollRect; if (prevScrollRect != null) { _target.scrollRect = null; } _grid = []; if (_target.parent == null) { _tempContainer.addChild(_target); } _bounds = _target.getBounds(_target.parent); var w:Number = 0; var h:Number = 0; _columns = Math.ceil(_bounds.width / _gridSize); _rows = Math.ceil(_bounds.height / _gridSize); var cumulativeHeight:Number = 0; var matrix:Matrix = _transform.matrix; var xOffset:Number = matrix.tx - _bounds.x; var yOffset:Number = matrix.ty - _bounds.y; if (!_smoothing) { xOffset = (xOffset + 0.5) >> 0; yOffset = (yOffset + 0.5) >> 0; } var bd:BitmapData, cumulativeWidth:Number; for (var row:int = 0; row < _rows; row++) { h = (_bounds.height - cumulativeHeight > _gridSize) ? _gridSize : _bounds.height - cumulativeHeight; matrix.ty = -cumulativeHeight + yOffset; cumulativeWidth = 0; _grid[row] = []; for (var column:int = 0; column < _columns; column++) { w = (_bounds.width - cumulativeWidth > _gridSize) ? _gridSize : _bounds.width - cumulativeWidth; _grid[row][column] = bd = new BitmapData(w + 1, h + 1, true, _fillColor); matrix.tx = -cumulativeWidth + xOffset; bd.draw(_target, matrix, null, null, _clipRect, _smoothing); cumulativeWidth += w; } cumulativeHeight += h; } if (_target.parent == _tempContainer) { _tempContainer.removeChild(_target); } if (prevMask != null) { _target.mask = prevMask; } if (prevScrollRect != null) { _target.scrollRect = prevScrollRect; } } /** @private **/ protected function _disposeGrid():void { var i:int = _grid.length; while (--i > -1) { var j:int = _grid[i].length; while (--j > -1) { BitmapData(_grid[i][j]).dispose(); } } } /** * Updates the BlitMask's internal bitmap to reflect the target's current position/scale/rotation. * This is a very important method that you'll need to call whenever visual or transformational changes are made * to the target so that the BlitMask remains synced with it. * * @param event An optional Event object (which isn't used at all internally) in order to make it easier to use update() as an event handler. For example, you could addEventListener(Event.ENTER_FRAME, myBlitMask.update) to make sure it is updated on every frame (although it would be more efficient to simply set autoUpdate to true in this case). * @param forceRecaptureBitmap Normally, the cached bitmap of the target is only recaptured if its scale or rotation changed because doing so is rather processor-intensive, but you can force a full update (and regeneration of the cached bitmap) by setting forceRecaptureBitmap to true. */ public function update(event:Event=null, forceRecaptureBitmap:Boolean=false):void { if (_target.parent) { _bounds = _target.getBounds(_target.parent); if (this.parent != _target.parent) { _target.parent.addChildAt(this, _target.parent.getChildIndex(_target)); } } if (_bitmapMode || forceRecaptureBitmap) { var m:Matrix = _transform.matrix; if (forceRecaptureBitmap || _prevMatrix == null || m.a != _prevMatrix.a || m.b != _prevMatrix.b || m.c != _prevMatrix.c || m.d != _prevMatrix.d) { _captureTargetBitmap(); _render(); } else if (m.tx != _prevMatrix.tx || m.ty != _prevMatrix.ty) { _render(); } _prevMatrix = m; } } /** @private **/ protected function _render():void { //note: the code in this method was optimized for speed rather than readability or succinctness (since the whole point of this class is to help things perform better) if (_bounds == null) { return; } _sliceRect.x = _sliceRect.y = 0; _sliceRect.width = _width + 1; _sliceRect.height = _height + 1; _bd.fillRect(_sliceRect, _fillColor); var x:Number = super.x; var y:Number = super.y; var g:Graphics = this.graphics; if (_bitmapMode) { this.filters = _target.filters; this.transform.colorTransform = _transform.colorTransform; } else { this.filters = _emptyArray; this.transform.colorTransform = _colorTransform; } if (x + _width < _bounds.x || y + _height < _bounds.y || x > _bounds.right || y > _bounds.bottom) { g.clear(); g.beginBitmapFill(_bd); g.drawRect(0, 0, _width, _height); g.endFill(); return; } var column:int = int((x - _bounds.x) / _gridSize); if (column < 0) { column = 0; } var row:int = int((y - _bounds.y) / _gridSize); if (row < 0) { row = 0; } var maxColumn:int = int(((x + _width) - _bounds.x) / _gridSize); if (maxColumn >= _columns) { maxColumn = _columns - 1; } var maxRow:uint = int(((y + _height) - _bounds.y) / _gridSize); if (maxRow >= _rows) { maxRow = _rows - 1; } if (y <= _bounds.y) { _destPoint.y = _bounds.y - y; _sliceRect.y = 0; } else { _destPoint.y = 0; _sliceRect.y = (y - _bounds.y) - (row * _gridSize); } if (x <= _bounds.x) { _destPoint.x = _bounds.x - x; if (!_smoothing) { _destPoint.x += 1; //necessary compensation (not entirely sure why yet) } _sliceRect.x = 0; } else { _destPoint.x = 0; _sliceRect.x = (x - _bounds.x) - (column * _gridSize); } //offset the values to avoid slight vibrations during animation. Adjust for these in the Matrix that gets passed to beginBitmapFill() var xOffset:Number = 1 - (_sliceRect.x % 1); if (xOffset > 0.5) { xOffset -= 1; } _sliceRect.x += xOffset - 1; //subtract 1 to make sure the whole image gets included - without this, a very slight vibration can occur on the edge during animation. var yOffset:Number = 1 - (_sliceRect.y % 1); if (yOffset > 0.5) { yOffset -= 1; } _sliceRect.y += yOffset - 1; var xDestReset:Number = _destPoint.x; var xSliceReset:Number = _sliceRect.x; var columnReset:int = column; var bd:BitmapData; if (_smoothing) { _drawRect.y = _destPoint.y; while (row <= maxRow) { bd = _grid[row][0]; _drawRect.height = bd.height - _sliceRect.y; _drawRect.x = xDestReset; _sliceRect.x = xSliceReset; column = columnReset; while (column <= maxColumn) { bd = _grid[row][column]; _drawRect.width = bd.width - _sliceRect.x; _tempMatrix.tx = _drawRect.x - _sliceRect.x; _tempMatrix.ty = _drawRect.y - _sliceRect.y; _bd.draw(bd, _tempMatrix, null, null, _drawRect, true); _drawRect.x += _drawRect.width - 1; _sliceRect.x = 0; column++; } _drawRect.y += _drawRect.height - 1; _sliceRect.y = 0; row++; } } else { _destPoint.y = (_destPoint.y + 0.5) >> 0; xDestReset = (xDestReset + 0.5) >> 0; xSliceReset = (xSliceReset + 0.5) >> 0; while (row <= maxRow) { bd = _grid[row][0]; _sliceRect.height = (bd.height - _sliceRect.y + 0.5) >> 0; _destPoint.x = xDestReset; _sliceRect.x = xSliceReset; column = columnReset; while (column <= maxColumn) { bd = _grid[row][column]; _sliceRect.width = bd.width - _sliceRect.x; _bd.copyPixels(bd, _sliceRect, _destPoint); _destPoint.x += _sliceRect.width - 1; _sliceRect.x = 0; column++; } _destPoint.y += _sliceRect.height - 1; _sliceRect.y = 0; row++; } } _tempMatrix.tx = xOffset - 1; //subtract 1 to compensate for the pixel we added above where we created the offset values. _tempMatrix.ty = yOffset - 1; g.clear(); g.beginBitmapFill(_bd, _tempMatrix, false, _smoothing); g.drawRect(0, 0, _width, _height); g.endFill(); } /** * Sets the width and height of the BlitMask. * Keep in mind that a BlitMask should not be rotated or scaled. * You can also directly set the width or height properties. * * @param width The width of the BlitMask * @param height The height of the BlitMask * @see #width * @see #height **/ public function setSize(width:Number, height:Number):void { if (_width == width && _height == height) { return; } else if (_bd != null) { _bd.dispose(); } _width = width; _height = height; _bd = new BitmapData(width + 1, height + 1, true, _fillColor); _render(); } /** @private **/ protected function _mouseEventPassthrough(event:MouseEvent):void { if (this.mouseEnabled && (!_bitmapMode || this.hitTestPoint(event.stageX, event.stageY, false))) { dispatchEvent(event); } } /** * Identical to setting bitmapMode = true but this method simplifies adding that * functionality to tweens or using it as an event handler. For example, to enable bitmapMode at * the beginning of a tween and then disable it when the tween completes, you could do:

* * TweenLite.to(mc, 3, {x:400, onStart:myBlitMask.enableBitmapMode, onUpdate:myBlitMask.update, onComplete:myBlitMask.disableBitmapMode}); * * * @param event An optional Event that isn't used internally but makes it possible to use the method as an event handler like addEventListener(MouseEvent.CLICK, myBlitMask.enableBitmapMode). * @see #disableBitmapMode() * @see #bitmapMode */ public function enableBitmapMode(event:Event=null):void { this.bitmapMode = true; } /** * Identical to setting bitmapMode = false but this method simplifies adding that * functionality to tweens or using it as an event handler. For example, to enable bitmapMode at * the beginning of a tween and then disable it when the tween completes, you could do:

* * TweenLite.to(mc, 3, {x:400, onStart:myBlitMask.enableBitmapMode, onUpdate:myBlitMask.update, onComplete:myBlitMask.disableBitmapMode}); * * * @param event An optional Event that isn't used internally but makes it possible to use the method as an event handler like addEventListener(MouseEvent.CLICK, myBlitMask.disableBitmapMode). * @see #enableBitmapMode() * @see #bitmapMode */ public function disableBitmapMode(event:Event=null):void { this.bitmapMode = false; } /** Disposes of the BlitMask and its internal BitmapData instances, releasing them for garbage collection. **/ public function dispose():void { _disposeGrid(); _bd.dispose(); this.bitmapMode = false; _target.mask = null; if (this.parent != null) { this.parent.removeChild(this); } this.target = null; } //---- GETTERS / SETTERS -------------------------------------------------------------------- /** * When true, the BlitMask optimizes itself for performance by setting the target's * visible property to false (greatly reducing the load on Flash's graphics rendering * routines) and uses its internally cached bitmap version of the target to redraw only the necessary * pixels inside the masked area. Since only a bitmap version of the target is shown while in bitmapMode, * the target won't be interactive. So if you have buttons and other objects that normally react to * MouseEvents, they won't while in bitmapMode. If you need the interactivity, simply set bitmapMode * to false and then it will turn the target's visible property back to true * and its mask property to the BlitMask itself. Typically it is best to turn bitmapMode on at least when you're * animating the target or the BlitMask itself, and then when the tween/animation is done and you need * interactivity, set bitmapMode back to false. For example:

* * var bm:BlitMask = new BlitMask(mc, 0, 0, 300, 200, true);

* * TweenLite.to(mc, 3, {x:200, onUpdate:bm.update, onComplete:completeHandler});

* * function completeHandler():void {
* bm.bitmapMode = false;
* }
*

* * @see #enableBitmapMode() * @see #disableBitmapMode() **/ public function get bitmapMode():Boolean { return _bitmapMode; } public function set bitmapMode(value:Boolean):void { if (_bitmapMode != value) { _bitmapMode = value; _target.visible = !_bitmapMode; update(null); if (_bitmapMode) { this.filters = _target.filters; this.transform.colorTransform = _transform.colorTransform; _target.mask = null; } else { this.filters = _emptyArray; this.transform.colorTransform = _colorTransform; this.cacheAsBitmap = false; //if cacheAsBitmap is true on both the _target and the BlitMask instance, the transparent areas of the mask will be...well...transparent which isn't what we want when bitmapMode is false (it could hide visible areas unless update(null, true) is called regularly, like if the target has animated children and bitmapMode is false) _target.mask = this; } if (_bitmapMode && _autoUpdate) { this.addEventListener(Event.ENTER_FRAME, update, false, -10, true); } else { this.removeEventListener(Event.ENTER_FRAME, update); } } } /** * If true, the BlitMask will automatically watch the target to see if * its position/scale/rotation has changed on each frame (while bitmapMode is true) * and if so, it will update() to make sure the BlitMask always stays synced with the target. * This is the easiest way to use BlitMask but it is slightly less efficient than manually calling update() * whenever you need to. Keep in mind that if you're tweening with TweenLite or TweenMax, you can simply set * its onUpdate to the BlitMask's update() method to keep things synced. * Like onUpdate:myBlitMask.update. **/ public function get autoUpdate():Boolean { return _autoUpdate; } public function set autoUpdate(value:Boolean):void { if (_autoUpdate != value) { _autoUpdate = value; if (_bitmapMode && _autoUpdate) { this.addEventListener(Event.ENTER_FRAME, update, false, -10, true); } else { this.removeEventListener(Event.ENTER_FRAME, update); } } } /** The target DisplayObject that the BlitMask should mask **/ public function get target():DisplayObject { return _target; } public function set target(value:DisplayObject):void { var i:int = _mouseEvents.length; if (_target != null) { while (--i > -1) { _target.removeEventListener(_mouseEvents[i], _mouseEventPassthrough); } } _target = value; if (_target != null) { i = _mouseEvents.length; while (--i > -1) { _target.addEventListener(_mouseEvents[i], _mouseEventPassthrough, false, 0, true); } _prevMatrix = null; _transform = _target.transform; update(null); } } /** x coordinate of the BlitMask (it will automatically be forced to whole pixel values if smoothing is false). **/ override public function get x():Number { return super.x; } override public function set x(value:Number):void { if (_smoothing) { super.x = value; } else if (value >= 0) { super.x = (value + 0.5) >> 0; } else { super.x = (value - 0.5) >> 0; } if (_bitmapMode) { _render(); } } /** y coordinate of the BlitMask (it will automatically be forced to whole pixel values if smoothing is false). **/ override public function get y():Number { return super.y; } override public function set y(value:Number):void { if (_smoothing) { super.y = value; } else if (value >= 0) { super.y = (value + 0.5) >> 0; } else { super.y = (value - 0.5) >> 0; } if (_bitmapMode) { _render(); } } /** Width of the BlitMask **/ override public function get width():Number { return _width; } override public function set width(value:Number):void { setSize(value, _height); } /** Height of the BlitMask **/ override public function get height():Number { return _height; } override public function set height(value:Number):void { setSize(_width, value); } /** scaleX (warning: altering the scaleX won't actually change its value - instead, it affects the width property accordingly) **/ override public function get scaleX():Number { return 1; } override public function set scaleX(value:Number):void { var oldScaleX:Number = _scaleX; _scaleX = value; setSize(_width * (_scaleX / oldScaleX), _height); } /** scaleY (warning: altering the scaleY won't actually change its value - instead, it affects the height property accordingly) **/ override public function get scaleY():Number { return 1; } override public function set scaleY(value:Number):void { var oldScaleY:Number = _scaleY; _scaleY = value; setSize(_width, _height * (_scaleY / oldScaleY)); } /** Rotation of the BlitMask (always 0 because BlitMasks can't be rotated!) **/ override public function set rotation(value:Number):void { if (value != 0) { throw new Error("Cannot set the rotation of a BlitMask to a non-zero number. BlitMasks should remain unrotated."); } } /** * Typically a value between 0 and 1 indicating the target's position in relation to the BlitMask * on the x-axis where 0 is at the beginning, 0.5 is scrolled to exactly the halfway point, and 1 is scrolled * all the way. This makes it very easy to animate the scroll. For example, to scroll from beginning to end * over 5 seconds, you could do:

* * myBlitMask.scrollX = 0;
* TweenLite.to(myBlitMask, 5, {scrollX:1}); *
* @see #scrollY **/ public function get scrollX():Number { return (super.x - _bounds.x) / (_bounds.width - _width); } public function set scrollX(value:Number):void { if (_target.parent) { _bounds = _target.getBounds(_target.parent); var dif:Number; dif = (super.x - (_bounds.width - _width) * value) - _bounds.x; _target.x += dif; _bounds.x += dif; if (_bitmapMode) { _render(); } } } /** * Typically a value between 0 and 1 indicating the target's position in relation to the BlitMask * on the y-axis where 0 is at the beginning, 0.5 is scrolled to exactly the halfway point, and 1 is scrolled * all the way. This makes it very easy to animate the scroll. For example, to scroll from beginning to end * over 5 seconds, you could do:

* * myBlitMask.scrollY = 0;
* TweenLite.to(myBlitMask, 5, {scrollY:1}); *
* @see #scrollX **/ public function get scrollY():Number { return (super.y - _bounds.y) / (_bounds.height - _height); } public function set scrollY(value:Number):void { if (_target.parent) { _bounds = _target.getBounds(_target.parent); var dif:Number = (super.y - (_bounds.height - _height) * value) - _bounds.y; _target.y += dif; _bounds.y += dif; if (_bitmapMode) { _render(); } } } /** If false (the default), the bitmap (and the BlitMask's x/y coordinates) will be rendered only on whole pixels which is faster in terms of processing. However, for the best quality and smoothest animation, set smoothing to true. **/ public function get smoothing():Boolean { return _smoothing; } public function set smoothing(value:Boolean):void { if (_smoothing != value) { _smoothing = value; _captureTargetBitmap(); if (_bitmapMode) { _render(); } } } /** The ARGB hexadecimal color that should fill the empty areas of the BlitMask. By default, it is transparent (0x00000000). If you wanted a red color, for example, it would be 0xFFFF0000. **/ public function get fillColor():uint { return _fillColor; } public function set fillColor(value:uint):void { if (_fillColor != value) { _fillColor = value; if (_bitmapMode) { _render(); } } } } }