PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/com/greensock/FlexBlitMask.as

https://bitbucket.org/tshubbard/zfstarlingtutorial
ActionScript | 925 lines | 588 code | 60 blank | 277 comment | 208 complexity | 9cf71484e9badb05e29c12dd44922bc2 MD5 | raw file
  1. /**
  2. * VERSION: 0.6
  3. * DATE: 2012-01-20
  4. * AS3
  5. * UPDATES AND DOCS AT: http://www.greensock.com
  6. **/
  7. package com.greensock {
  8. import flash.display.BitmapData;
  9. import flash.display.DisplayObject;
  10. import flash.display.Graphics;
  11. import flash.display.BlendMode;
  12. import flash.display.Sprite;
  13. import flash.events.Event;
  14. import flash.events.MouseEvent;
  15. import flash.geom.ColorTransform;
  16. import flash.geom.Matrix;
  17. import flash.geom.Point;
  18. import flash.geom.Rectangle;
  19. import flash.geom.Transform;
  20. import mx.core.UIComponent;
  21. /**
  22. * A FlexBlitMask is basically a rectangular UIComponent that acts as a high-performance mask for a DisplayObject
  23. * by caching a bitmap version of it and blitting only the pixels that should be visible at any given time,
  24. * although its <code>bitmapMode</code> can be turned off to restore interactivity in the DisplayObject
  25. * whenever you want. It is a Flex-friendly version of BlitMask. When scrolling very large images or text
  26. * blocks, a FlexBlitMask can greatly improve performance, especially on mobile devices that have weaker
  27. * processors. <br /><br />
  28. *
  29. * Here are some of the conveniences FlexBlitMask offers:<br />
  30. * <ul>
  31. * <li>Excellent scrolling performance</li>
  32. * <li>You don't need to do anything special with your target DisplayObject - move/scale/rotate it
  33. * however you please and then <code>update()</code> the FlexBlitMask and it syncs the pixels.
  34. * The FlexBlitMask basically sits on top of the DisplayObject in the display list and you can
  35. * move it independently too if you want.</li>
  36. * <li>Use the FlexBlitMask's <code>scrollX</code> and <code>scrollY</code> properties to move the
  37. * target DisplayObject inside the masked area. For example, to scroll from top to bottom over
  38. * the course of 2 seconds, simply do: <br /><code>myFlexBlitMask.scrollY = 0;<br />
  39. * TweenLite.to(myFlexBlitMask, 2, {scrollY:1});</code> </li>
  40. * <li>Use the "wrap" feature to make the bitmap wrap around to the opposite side when it scrolls
  41. * off one of the edges (only in <code>bitmapMode</code> of course), as though the FlexBlitMask is
  42. * filled with a grid of bitmap copies of the target.</li>
  43. * <li>For maximum <i>performance</i> in bitmapMode, set <code>smoothing</code> to <code>false</code> or
  44. * for maximum <i>quality</i>, set it to <code>true</code></li>
  45. * <li>You can toggle the <code>bitmapMode</code> to get either maximum performance or interactivity
  46. * in the target DisplayObject anytime. (some other solutions out there are only viable for
  47. * non-interactive bitmap content) </li>
  48. * <li>MouseEvents are dispatched by the FlexBlitMask, so you can listen for clicks, rollovers, rollouts, etc.</li>
  49. * </ul>
  50. *
  51. * @example Example AS3 code:<listing version="3.0">
  52. &lt;?xml version="1.0" encoding="utf-8"?&gt;
  53. &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" frameRate="60" layout="absolute" xmlns:greensock="com.greensock.~~" creationComplete="tween()"&gt;
  54. &lt;mx:Script&gt;
  55. &lt;![CDATA[
  56. import com.greensock.TweenLite;
  57. private function tween():void {
  58. myText.y = 50;
  59. TweenLite.to(myText, 6, {y:-100});
  60. }
  61. ]]&gt;
  62. &lt;/mx:Script&gt;
  63. &lt;greensock:FlexBlitMask id="blitMask" target="{myText}" wrap="false" x="20" y="50" width="300" height="200" smoothing="true" /&gt;
  64. &lt;mx:Label text="FlexBlitMask Example" fontSize="24" /&gt;
  65. &lt;mx:Text id="myText" x="20" y="50" width="135" height="500" text="FlexBlitMask can be great for high-performance scrolling. Performance is of paramount importance in mobile apps. There is, of course, a trade-off in memory because an extra bitmap version of the target needs to be captured/maintained, but overall performance while scrolling can be significantly improved. It doesn't make sense to use FlexBlitMask if you're tweening the scale or rotation of the target, though - it is primarily for scrolling (tweening the x and/or y properties)." /&gt;
  66. &lt;mx:Button id="tweenButton" label="Tween" x="20" y="260" click="tween()" /&gt;
  67. &lt;/mx:Application&gt;
  68. </listing>
  69. *
  70. * Notes:
  71. * <ul>
  72. * <li>FlexBlitMasks themselves should not be rotated or scaled (although technically you can alter the scaleX and scaleY
  73. * but doing so will only change the width or height instead). You can, of course, alter their x, y, width,
  74. * or height properties as much as you want. </li>
  75. * <li>FlexBlitMasks don't perform nearly as well in bitmapMode when the <code>target</code> is being scaled or rotated
  76. * because it forces a flushing and recapture of the internal bitmap. FlexBlitMasks are <b>MUCH</b> better when you are
  77. * simply changing x/y properties (scrolling) because it can reuse the same cached bitmap over and over.</li>
  78. * <li>If the target content is changing frequently (like if it has nested MovieClips that are animating on every frame),
  79. * you'd need to call update(null, true) each time you want the FlexBlitMask to redraw itself to sync with the changes
  80. * in the target, but that's a relatively expensive operation so it's not a great use case for FlexBlitMask. You may
  81. * be better off just turning off bitmapMode during that animation sequence.</li>
  82. * </ul><br /><br />
  83. *
  84. * <b>Copyright 2011-2012, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
  85. *
  86. * @author Jack Doyle, jack@greensock.com
  87. **/
  88. public class FlexBlitMask extends UIComponent {
  89. /** @private **/
  90. public static var version:Number = 0.6;
  91. // 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.
  92. /** @private **/
  93. protected static var _tempContainer:Sprite = new Sprite();
  94. /** @private **/
  95. protected static var _sliceRect:Rectangle = new Rectangle();
  96. /** @private **/
  97. protected static var _drawRect:Rectangle = new Rectangle();
  98. /** @private **/
  99. protected static var _destPoint:Point = new Point();
  100. /** @private **/
  101. protected static var _tempMatrix:Matrix = new Matrix();
  102. /** @private **/
  103. protected static var _emptyArray:Array = [];
  104. /** @private **/
  105. protected static var _colorTransform:ColorTransform = new ColorTransform();
  106. /** @private **/
  107. 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];
  108. /** @private **/
  109. protected var _target:DisplayObject;
  110. /** @private **/
  111. protected var _fillColor:uint;
  112. /** @private **/
  113. protected var _smoothing:Boolean;
  114. /** @private **/
  115. protected var _width:Number;
  116. /** @private **/
  117. protected var _height:Number;
  118. /** @private **/
  119. protected var _bd:BitmapData;
  120. /** @private maximum number of pixels (minus one) that each BitmapData cell in the grid can be **/
  121. protected var _gridSize:int = 2879;
  122. /** @private **/
  123. protected var _grid:Array;
  124. /** @private **/
  125. protected var _bounds:Rectangle;
  126. /** @private **/
  127. protected var _clipRect:Rectangle;
  128. /** @private **/
  129. protected var _bitmapMode:Boolean;
  130. /** @private **/
  131. protected var _rows:int;
  132. /** @private **/
  133. protected var _columns:int;
  134. /** @private **/
  135. protected var _scaleX:Number;
  136. /** @private **/
  137. protected var _scaleY:Number;
  138. /** @private **/
  139. protected var _prevMatrix:Matrix;
  140. /** @private **/
  141. protected var _transform:Transform;
  142. /** @private **/
  143. protected var _prevRotation:Number;
  144. /** @private **/
  145. protected var _autoUpdate:Boolean;
  146. /** @private **/
  147. protected var _wrap:Boolean;
  148. /** @private **/
  149. protected var _wrapOffsetX:Number = 0;
  150. /** @private **/
  151. protected var _wrapOffsetY:Number = 0;
  152. /**
  153. * Constructor
  154. *
  155. * @param target The DisplayObject that will be masked by the FlexBlitMask
  156. * @param x x coorinate of the upper left corner of the FlexBlitMask. If <code>smoothing</code> is <code>false</code>, the x coordinate will be rounded to the closest integer.
  157. * @param y y coordinate of the upper right corner of the FlexBlitMask
  158. * @param width width of the FlexBlitMask (in pixels)
  159. * @param height height of the FlexBlitMask (in pixels)
  160. * @param smoothing If <code>false</code> (the default), the bitmap (and the FlexBlitMask'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 <code>smoothing</code> to <code>true</code>.
  161. * @param autoUpdate If <code>true</code> (the default), the FlexBlitMask will automatically watch the <code>target</code> to see if its position/scale/rotation has changed on each frame (while <code>bitmapMode</code> is <code>true</code>) and if so, it will <code>update()</code> to make sure the FlexBlitMask always stays synced with the <code>target</code>. This is the easiest way to use FlexBlitMask but it is slightly less efficient than manually calling <code>update()</code> whenever you need to. Keep in mind that if you're tweening with TweenLite or TweenMax, you can simply set its <code>onUpdate</code> to the FlexBlitMask's <code>update()</code> method to keep things synced. Like <code>onUpdate:myFlexBlitMask.update</code>.
  162. * @param fillColor The ARGB hexadecimal color that should fill the empty areas of the FlexBlitMask. By default, it is transparent (0x00000000). If you wanted a red color, for example, it would be <code>0xFFFF0000</code>.
  163. * @param wrap If <code>true</code>, the bitmap will be wrapped around to the opposite side when it scrolls off one of the edges (only in <code>bitmapMode</code> of course), like the FlexBlitMask is filled with a grid of bitmap copies of the target. Use the <code>wrapOffsetX</code> and <code>wrapOffsetY</code> properties to affect how far apart the copies are from each other.
  164. */
  165. public function FlexBlitMask(target:DisplayObject=null, x:Number=0, y:Number=0, width:Number=100, height:Number=100, smoothing:Boolean=false, autoUpdate:Boolean=true, fillColor:uint=0x00000000, wrap:Boolean=false) {
  166. super();
  167. if (width < 0 || height < 0) {
  168. throw new Error("A FlexBlitMask cannot have a negative width or height.");
  169. }
  170. _width = width;
  171. _height = height;
  172. _scaleX = _scaleY = 1;
  173. _smoothing = smoothing;
  174. _fillColor = fillColor;
  175. _autoUpdate = autoUpdate;
  176. _wrap = wrap;
  177. _grid = [];
  178. _bounds = new Rectangle();
  179. if (_smoothing) {
  180. super.x = x;
  181. super.y = y;
  182. } else {
  183. super.x = (x < 0) ? (x - 0.5) >> 0 : (x + 0.5) >> 0;
  184. super.y = (y < 0) ? (y - 0.5) >> 0 : (y + 0.5) >> 0;
  185. }
  186. _clipRect = new Rectangle(0, 0, _gridSize + 1, _gridSize + 1);
  187. _bd = new BitmapData(width + 1, height + 1, true, _fillColor);
  188. _bitmapMode = true;
  189. this.target = target;
  190. }
  191. /** @private **/
  192. protected function _captureTargetBitmap():void {
  193. if (_bd == null || _target == null) { //must have been disposed, so don't update.
  194. return;
  195. }
  196. _disposeGrid();
  197. //capturing when the target is masked (or has a scrollRect) can cause problems.
  198. var prevMask:DisplayObject = _target.mask;
  199. if (prevMask != null) {
  200. _target.mask = null;
  201. }
  202. var prevScrollRect:Rectangle = _target.scrollRect;
  203. if (prevScrollRect != null) {
  204. _target.scrollRect = null;
  205. }
  206. var prevFilters:Array = _target.filters;
  207. if (prevFilters.length != 0) {
  208. _target.filters = _emptyArray;
  209. }
  210. _grid = [];
  211. if (_target.parent == null) {
  212. _tempContainer.addChild(_target);
  213. }
  214. _bounds = _target.getBounds(_target.parent);
  215. var w:Number = 0;
  216. var h:Number = 0;
  217. _columns = Math.ceil(_bounds.width / _gridSize);
  218. _rows = Math.ceil(_bounds.height / _gridSize);
  219. var cumulativeHeight:Number = 0;
  220. var matrix:Matrix = _transform.matrix;
  221. var xOffset:Number = matrix.tx - _bounds.x;
  222. var yOffset:Number = matrix.ty - _bounds.y;
  223. if (!_smoothing) {
  224. xOffset = (xOffset + 0.5) >> 0;
  225. yOffset = (yOffset + 0.5) >> 0;
  226. }
  227. var bd:BitmapData, cumulativeWidth:Number;
  228. for (var row:int = 0; row < _rows; row++) {
  229. h = (_bounds.height - cumulativeHeight > _gridSize) ? _gridSize : _bounds.height - cumulativeHeight;
  230. matrix.ty = -cumulativeHeight + yOffset;
  231. cumulativeWidth = 0;
  232. _grid[row] = [];
  233. for (var column:int = 0; column < _columns; column++) {
  234. w = (_bounds.width - cumulativeWidth > _gridSize) ? _gridSize : _bounds.width - cumulativeWidth;
  235. _grid[row][column] = bd = new BitmapData(w + 1, h + 1, true, _fillColor);
  236. matrix.tx = -cumulativeWidth + xOffset;
  237. bd.draw(_target, matrix, null, null, _clipRect, _smoothing);
  238. cumulativeWidth += w;
  239. }
  240. cumulativeHeight += h;
  241. }
  242. if (_target.parent == _tempContainer) {
  243. _tempContainer.removeChild(_target);
  244. }
  245. if (prevMask != null) {
  246. _target.mask = prevMask;
  247. }
  248. if (prevScrollRect != null) {
  249. _target.scrollRect = prevScrollRect;
  250. }
  251. if (prevFilters.length != 0) {
  252. _target.filters = prevFilters;
  253. }
  254. }
  255. /** @private **/
  256. protected function _disposeGrid():void {
  257. var i:int = _grid.length, j:int, r:Array;
  258. while (--i > -1) {
  259. r = _grid[i];
  260. j = r.length;
  261. while (--j > -1) {
  262. BitmapData(r[j]).dispose();
  263. }
  264. }
  265. }
  266. /**
  267. * Updates the FlexBlitMask's internal bitmap to reflect the <code>target's</code> current position/scale/rotation.
  268. * This is a very important method that you'll need to call whenever visual or transformational changes are made
  269. * to the target so that the FlexBlitMask remains synced with it.
  270. *
  271. * @param event An optional Event object (which isn't used at all internally) in order to make it easier to use <code>update()</code> as an event handler. For example, you could <code>addEventListener(Event.ENTER_FRAME, myFlexBlitMask.update)</code> to make sure it is updated on every frame (although it would be more efficient to simply set <code>autoUpdate</code> to <code>true</code> in this case).
  272. * @param forceRecaptureBitmap Normally, the cached bitmap of the <code>target</code> 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 <code>forceRecaptureBitmap</code> to <code>true</code>.
  273. */
  274. public function update(event:Event=null, forceRecaptureBitmap:Boolean=false):void {
  275. if (_bd == null) {
  276. return;
  277. } else if (_target == null) {
  278. _render();
  279. } else if (_target.parent) {
  280. _bounds = _target.getBounds(_target.parent);
  281. if (this.parent != _target.parent) {
  282. if (_target.parent.hasOwnProperty("addElementAt")) { //for Flex compatibility (spark)
  283. Object(_target.parent).addElementAt(this, Object(_target.parent).getChildIndex(_target));
  284. } else {
  285. _target.parent.addChildAt(this, _target.parent.getChildIndex(_target));
  286. }
  287. }
  288. }
  289. if (_bitmapMode || forceRecaptureBitmap) {
  290. var m:Matrix = _transform.matrix;
  291. if (forceRecaptureBitmap || _prevMatrix == null || m.a != _prevMatrix.a || m.b != _prevMatrix.b || m.c != _prevMatrix.c || m.d != _prevMatrix.d) {
  292. _captureTargetBitmap();
  293. _render();
  294. } else if (m.tx != _prevMatrix.tx || m.ty != _prevMatrix.ty) {
  295. _render();
  296. } else if (_bitmapMode && _target != null) {
  297. this.filters = _target.filters;
  298. this.transform.colorTransform = _transform.colorTransform;
  299. }
  300. _prevMatrix = m;
  301. }
  302. }
  303. /** @private **/
  304. protected function _render(xOffset:Number=0, yOffset:Number=0, clear:Boolean=true, limitRecursion:Boolean=false):void {
  305. //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)
  306. if (clear) {
  307. _sliceRect.x = _sliceRect.y = 0;
  308. _sliceRect.width = _width + 1;
  309. _sliceRect.height = _height + 1;
  310. _bd.fillRect(_sliceRect, _fillColor);
  311. if (_bitmapMode && _target != null) {
  312. this.filters = _target.filters;
  313. this.transform.colorTransform = _transform.colorTransform;
  314. } else {
  315. this.filters = _emptyArray;
  316. this.transform.colorTransform = _colorTransform;
  317. }
  318. }
  319. if (_bd == null) {
  320. return;
  321. } else if (_rows == 0) { //sometimes (especially in Flex) objects take a frame or two to render in Flash and properly report their width/height. Before that, their width/height is typically 0. This works around that issue and forces a refresh if we didn't capture any pixels last time we did a capture.
  322. _captureTargetBitmap();
  323. }
  324. var x:Number = super.x + xOffset;
  325. var y:Number = super.y + yOffset;
  326. var wrapWidth:int = (_bounds.width + _wrapOffsetX + 0.5) >> 0;
  327. var wrapHeight:int = (_bounds.height + _wrapOffsetY + 0.5) >> 0;
  328. var g:Graphics = this.graphics;
  329. if (_bounds.width == 0 || _bounds.height == 0 || (_wrap && (wrapWidth == 0 || wrapHeight == 0)) || (!_wrap && (x + _width < _bounds.x || y + _height < _bounds.y || x > _bounds.right || y > _bounds.bottom))) {
  330. g.clear();
  331. g.beginBitmapFill(_bd);
  332. g.drawRect(0, 0, _width, _height);
  333. g.endFill();
  334. return;
  335. }
  336. var column:int = int((x - _bounds.x) / _gridSize);
  337. if (column < 0) {
  338. column = 0;
  339. }
  340. var row:int = int((y - _bounds.y) / _gridSize);
  341. if (row < 0) {
  342. row = 0;
  343. }
  344. var maxColumn:int = int(((x + _width) - _bounds.x) / _gridSize);
  345. if (maxColumn >= _columns) {
  346. maxColumn = _columns - 1;
  347. }
  348. var maxRow:uint = int(((y + _height) - _bounds.y) / _gridSize);
  349. if (maxRow >= _rows) {
  350. maxRow = _rows - 1;
  351. }
  352. var xNudge:Number = (_bounds.x - x) % 1;
  353. var yNudge:Number = (_bounds.y - y) % 1;
  354. if (y <= _bounds.y) {
  355. _destPoint.y = (_bounds.y - y) >> 0;
  356. _sliceRect.y = -1; //subtract 1 to make sure the whole image gets included - without this, a very slight vibration can occur on the edge during animation.
  357. } else {
  358. _destPoint.y = 0;
  359. _sliceRect.y = Math.ceil(y - _bounds.y) - (row * _gridSize) - 1; //subtract 1 to make sure the whole image gets included - without this, a very slight vibration can occur on the edge during animation.
  360. if (clear && yNudge != 0) {
  361. yNudge += 1;
  362. }
  363. }
  364. if (x <= _bounds.x) {
  365. _destPoint.x = (_bounds.x - x) >> 0;
  366. _sliceRect.x = -1; //subtract 1 to make sure the whole image gets included - without this, a very slight vibration can occur on the edge during animation.
  367. } else {
  368. _destPoint.x = 0;
  369. _sliceRect.x = Math.ceil(x - _bounds.x) - (column * _gridSize) - 1; //subtract 1 to make sure the whole image gets included - without this, a very slight vibration can occur on the edge during animation.
  370. if (clear && xNudge != 0) {
  371. xNudge += 1;
  372. }
  373. }
  374. if (_wrap && clear) {
  375. //make sure to offset appropriately so that we start drawing directly on the image. We must use consistent xNudge and yNudge values across all the recursive calls too, otherwise the copies may vibrate visually a bit as they move
  376. _render(Math.ceil((_bounds.x - x) / wrapWidth) * wrapWidth, Math.ceil((_bounds.y - y) / wrapHeight) * wrapHeight, false, false);
  377. } else if (_rows != 0) {
  378. var xDestReset:Number = _destPoint.x;
  379. var xSliceReset:Number = _sliceRect.x;
  380. var columnReset:int = column;
  381. var bd:BitmapData;
  382. while (row <= maxRow) {
  383. bd = _grid[row][0];
  384. _sliceRect.height = bd.height - _sliceRect.y;
  385. _destPoint.x = xDestReset;
  386. _sliceRect.x = xSliceReset;
  387. column = columnReset;
  388. while (column <= maxColumn) {
  389. bd = _grid[row][column];
  390. _sliceRect.width = bd.width - _sliceRect.x;
  391. _bd.copyPixels(bd, _sliceRect, _destPoint);
  392. _destPoint.x += _sliceRect.width - 1;
  393. _sliceRect.x = 0;
  394. column++;
  395. }
  396. _destPoint.y += _sliceRect.height - 1;
  397. _sliceRect.y = 0;
  398. row++;
  399. }
  400. }
  401. if (clear) {
  402. _tempMatrix.tx = xNudge - 1; //subtract 1 to compensate for the pixel we added above.
  403. _tempMatrix.ty = yNudge - 1;
  404. g.clear();
  405. g.beginBitmapFill(_bd, _tempMatrix, false, _smoothing);
  406. g.drawRect(0, 0, _width, _height);
  407. g.endFill();
  408. } else if (_wrap) {
  409. //if needed, recursively call _render() and adjust the offset(s) to wrap the bitmap.
  410. if (x + _width > _bounds.right) {
  411. _render(xOffset - wrapWidth, yOffset, false, true);
  412. }
  413. if (!limitRecursion && y + _height > _bounds.bottom) {
  414. _render(xOffset, yOffset - wrapHeight, false, false);
  415. }
  416. }
  417. }
  418. /**
  419. * Sets the width and height of the FlexBlitMask.
  420. * Keep in mind that a FlexBlitMask should not be rotated or scaled.
  421. * You can also directly set the <code>width</code> or <code>height</code> properties.
  422. *
  423. * @param width The width of the FlexBlitMask
  424. * @param height The height of the FlexBlitMask
  425. * @see #width
  426. * @see #height
  427. **/
  428. public function setSize(width:Number, height:Number):void {
  429. if (_width == width && _height == height) {
  430. return;
  431. } else if (width < 0 || height < 0) {
  432. throw new Error("A FlexBlitMask cannot have a negative width or height.");
  433. } else if (_bd != null) {
  434. _bd.dispose();
  435. }
  436. _width = width;
  437. _height = height;
  438. _bd = new BitmapData(width + 1, height + 1, true, _fillColor);
  439. _render();
  440. }
  441. /** @private **/
  442. protected function _mouseEventPassthrough(event:MouseEvent):void {
  443. if (this.mouseEnabled && (!_bitmapMode || this.hitTestPoint(event.stageX, event.stageY, false))) {
  444. dispatchEvent(event);
  445. }
  446. }
  447. /**
  448. * Identical to setting <code>bitmapMode = true</code> but this method simplifies adding that
  449. * functionality to tweens or using it as an event handler. For example, to enable bitmapMode at
  450. * the beginning of a tween and then disable it when the tween completes, you could do: <br /><br /><code>
  451. *
  452. * TweenLite.to(mc, 3, {x:400, onStart:myFlexBlitMask.enableBitmapMode, onUpdate:myFlexBlitMask.update, onComplete:myFlexBlitMask.disableBitmapMode});
  453. * </code>
  454. *
  455. * @param event An optional Event that isn't used internally but makes it possible to use the method as an event handler like <code>addEventListener(MouseEvent.CLICK, myFlexBlitMask.enableBitmapMode)</code>.
  456. * @see #disableBitmapMode()
  457. * @see #bitmapMode
  458. */
  459. public function enableBitmapMode(event:Event=null):void {
  460. this.bitmapMode = true;
  461. }
  462. /**
  463. * Identical to setting <code>bitmapMode = false</code> but this method simplifies adding that
  464. * functionality to tweens or using it as an event handler. For example, to enable bitmapMode at
  465. * the beginning of a tween and then disable it when the tween completes, you could do: <br /><br /><code>
  466. *
  467. * TweenLite.to(mc, 3, {x:400, onStart:myFlexBlitMask.enableBitmapMode, onUpdate:myFlexBlitMask.update, onComplete:myFlexBlitMask.disableBitmapMode});
  468. * </code>
  469. *
  470. * @param event An optional Event that isn't used internally but makes it possible to use the method as an event handler like <code>addEventListener(MouseEvent.CLICK, myFlexBlitMask.disableBitmapMode)</code>.
  471. * @see #enableBitmapMode()
  472. * @see #bitmapMode
  473. */
  474. public function disableBitmapMode(event:Event=null):void {
  475. this.bitmapMode = false;
  476. }
  477. /**
  478. * Repositions the <code>target</code> so that it is visible within the BlitMask, as though <code>wrap</code>
  479. * was enabled (this method is called automatically when <code>bitmapMode</code> is disabled while <code>wrap</code>
  480. * is <code>true</code>). For example, if you tween the <code>target</code> way off the edge of the BlitMask and
  481. * have <code>wrap</code> enabled, it will appear to come back in from the other side even though the raw coordinates
  482. * of the target would indicate that it is outside the BlitMask. If you want to force the coordinates to normalize
  483. * so that they reflect that wrapped position, simply call <code>normalizePosition()</code>. It will automatically
  484. * choose the coordinates that would maximize the visible portion of the target if a seam is currently showing.
  485. **/
  486. public function normalizePosition():void {
  487. if (_target && _bounds) {
  488. var wrapWidth:int = (_bounds.width + _wrapOffsetX + 0.5) >> 0;
  489. var wrapHeight:int = (_bounds.height + _wrapOffsetY + 0.5) >> 0;
  490. var offsetX:Number = (_bounds.x - this.x) % wrapWidth;
  491. var offsetY:Number = (_bounds.y - this.y) % wrapHeight;
  492. if (offsetX > (_width + _wrapOffsetX) / 2) {
  493. offsetX -= wrapWidth;
  494. } else if (offsetX < (_width + _wrapOffsetX) / -2) {
  495. offsetX += wrapWidth;
  496. }
  497. if (offsetY > (_height + _wrapOffsetY) / 2) {
  498. offsetY -= wrapHeight;
  499. } else if (offsetY < (_height + _wrapOffsetY) / -2) {
  500. offsetY += wrapHeight;
  501. }
  502. _target.x += this.x + offsetX - _bounds.x;
  503. _target.y += this.y + offsetY - _bounds.y;
  504. }
  505. }
  506. /** Disposes of the FlexBlitMask and its internal BitmapData instances, releasing them for garbage collection. **/
  507. public function dispose():void {
  508. if (_bd == null) { //already disposed.
  509. return;
  510. }
  511. _disposeGrid();
  512. _bd.dispose();
  513. _bd = null;
  514. this.bitmapMode = false;
  515. this.autoUpdate = false;
  516. if (_target != null) {
  517. _target.mask = null;
  518. }
  519. if (this.parent != null) {
  520. if (this.parent.hasOwnProperty("removeElement")) {
  521. Object(this.parent).removeElement(this); //for Flex compatibility (spark)
  522. } else {
  523. this.parent.removeChild(this);
  524. }
  525. }
  526. this.target = null;
  527. }
  528. /** @private **/
  529. override protected function measure():void {
  530. if (this.parent) {
  531. var bounds:Rectangle = this.getBounds(this.parent);
  532. super.width = bounds.width;
  533. super.height = bounds.height;
  534. }
  535. this.explicitWidth = _width;
  536. this.explicitHeight = _height;
  537. super.measure();
  538. }
  539. /** @inheritDoc **/
  540. override public function setActualSize(w:Number, h:Number):void {
  541. setSize(w, h);
  542. super.setActualSize(w, h);
  543. }
  544. //---- GETTERS / SETTERS --------------------------------------------------------------------
  545. /**
  546. * When <code>true</code>, the FlexBlitMask optimizes itself for performance by setting the <code>target's</code>
  547. * <code>visible</code> property to <code>false</code> (greatly reducing the load on Flash's graphics rendering
  548. * routines) and uses its internally cached bitmap version of the <code>target</code> to redraw only the necessary
  549. * pixels inside the masked area. Since only a bitmap version of the <code>target</code> is shown while in bitmapMode,
  550. * the <code>target</code> won't be interactive. So if you have buttons and other objects that normally react to
  551. * MouseEvents, they won't while in bitmapMode. If you need the interactivity, simply set <code>bitmapMode</code>
  552. * to <code>false</code> and then it will turn the <code>target's</code> <code>visible</code> property back to <code>true</code>
  553. * and its <code>mask</code> property to the FlexBlitMask itself. Typically it is best to turn bitmapMode on at least when you're
  554. * animating the <code>target</code> or the FlexBlitMask itself, and then when the tween/animation is done and you need
  555. * interactivity, set bitmapMode back to false. For example: <br /><br /><code>
  556. *
  557. * var bm:FlexBlitMask = new FlexBlitMask(mc, 0, 0, 300, 200, true);<br /><br />
  558. *
  559. * TweenLite.to(mc, 3, {x:200, onUpdate:bm.update, onComplete:completeHandler});<br /><br />
  560. *
  561. * function completeHandler():void {<br />
  562. * bm.bitmapMode = false;<br />
  563. * }<br />
  564. * </code><br /><br />
  565. *
  566. * @see #enableBitmapMode()
  567. * @see #disableBitmapMode()
  568. **/
  569. public function get bitmapMode():Boolean {
  570. return _bitmapMode;
  571. }
  572. public function set bitmapMode(value:Boolean):void {
  573. if (_bitmapMode != value) {
  574. _bitmapMode = value;
  575. if (_target != null) {
  576. _target.visible = !_bitmapMode;
  577. update(null);
  578. if (_bitmapMode) {
  579. this.filters = _target.filters;
  580. this.transform.colorTransform = _transform.colorTransform;
  581. if (_target.blendMode == "auto") {
  582. this.blendMode = (_target.alpha == 0 || _target.alpha == 1) ? BlendMode.NORMAL : BlendMode.LAYER;
  583. } else {
  584. this.blendMode = _target.blendMode;
  585. }
  586. _target.mask = null;
  587. } else {
  588. this.filters = _emptyArray;
  589. this.transform.colorTransform = _colorTransform;
  590. this.blendMode = "normal";
  591. this.cacheAsBitmap = false; //if cacheAsBitmap is true on both the _target and the FlexBlitMask 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)
  592. _target.mask = this;
  593. if (_wrap) {
  594. normalizePosition();
  595. }
  596. }
  597. if (_bitmapMode && _autoUpdate) {
  598. this.addEventListener(Event.ENTER_FRAME, update, false, -10, true);
  599. } else {
  600. this.removeEventListener(Event.ENTER_FRAME, update);
  601. }
  602. }
  603. }
  604. }
  605. /**
  606. * If <code>true</code>, the FlexBlitMask will automatically watch the <code>target</code> to see if
  607. * its position/scale/rotation has changed on each frame (while <code>bitmapMode</code> is <code>true</code>)
  608. * and if so, it will <code>update()</code> to make sure the FlexBlitMask always stays synced with the <code>target</code>.
  609. * This is the easiest way to use FlexBlitMask but it is slightly less efficient than manually calling <code>update()</code>
  610. * whenever you need to. Keep in mind that if you're tweening with TweenLite or TweenMax, you can simply set
  611. * its <code>onUpdate</code> to the FlexBlitMask's <code>update()</code> method to keep things synced.
  612. * Like <code>onUpdate:myFlexBlitMask.update</code>.
  613. **/
  614. public function get autoUpdate():Boolean {
  615. return _autoUpdate;
  616. }
  617. public function set autoUpdate(value:Boolean):void {
  618. if (_autoUpdate != value) {
  619. _autoUpdate = value;
  620. if (_bitmapMode && _autoUpdate) {
  621. this.addEventListener(Event.ENTER_FRAME, update, false, -10, true);
  622. } else {
  623. this.removeEventListener(Event.ENTER_FRAME, update);
  624. }
  625. }
  626. }
  627. /** The target DisplayObject that the FlexBlitMask should mask **/
  628. public function get target():DisplayObject {
  629. return _target;
  630. }
  631. public function set target(value:DisplayObject):void {
  632. if (_target != value) {
  633. var i:int = _mouseEvents.length;
  634. if (_target != null) {
  635. while (--i > -1) {
  636. _target.removeEventListener(_mouseEvents[i], _mouseEventPassthrough);
  637. }
  638. }
  639. _target = value;
  640. if (_target != null) {
  641. i = _mouseEvents.length;
  642. while (--i > -1) {
  643. _target.addEventListener(_mouseEvents[i], _mouseEventPassthrough, false, 0, true);
  644. }
  645. _prevMatrix = null;
  646. _transform = _target.transform;
  647. _bitmapMode = !_bitmapMode;
  648. this.bitmapMode = !_bitmapMode; //forces a refresh (applying the mask, doing an update(), etc.)
  649. } else {
  650. _bounds = new Rectangle();
  651. }
  652. }
  653. }
  654. /** x coordinate of the FlexBlitMask (it will automatically be forced to whole pixel values if <code>smoothing</code> is <code>false</code>). **/
  655. override public function get x():Number {
  656. return super.x;
  657. }
  658. override public function set x(value:Number):void {
  659. if (_smoothing) {
  660. super.x = value;
  661. } else if (value >= 0) {
  662. super.x = (value + 0.5) >> 0;
  663. } else {
  664. super.x = (value - 0.5) >> 0;
  665. }
  666. if (_bitmapMode) {
  667. _render();
  668. }
  669. }
  670. /** y coordinate of the FlexBlitMask (it will automatically be forced to whole pixel values if <code>smoothing</code> is <code>false</code>). **/
  671. override public function get y():Number {
  672. return super.y;
  673. }
  674. override public function set y(value:Number):void {
  675. if (_smoothing) {
  676. super.y = value;
  677. } else if (value >= 0) {
  678. super.y = (value + 0.5) >> 0;
  679. } else {
  680. super.y = (value - 0.5) >> 0;
  681. }
  682. if (_bitmapMode) {
  683. _render();
  684. }
  685. }
  686. /** Width of the FlexBlitMask **/
  687. override public function get width():Number {
  688. return _width;
  689. }
  690. override public function set width(value:Number):void {
  691. setSize(value, _height);
  692. }
  693. /** Height of the FlexBlitMask **/
  694. override public function get height():Number {
  695. return _height;
  696. }
  697. override public function set height(value:Number):void {
  698. setSize(_width, value);
  699. }
  700. /** scaleX (warning: altering the scaleX won't actually change its value - instead, it affects the <code>width</code> property accordingly) **/
  701. override public function get scaleX():Number {
  702. return 1;
  703. }
  704. override public function set scaleX(value:Number):void {
  705. var oldScaleX:Number = _scaleX;
  706. _scaleX = value;
  707. setSize(_width * (_scaleX / oldScaleX), _height);
  708. }
  709. /** scaleY (warning: altering the scaleY won't actually change its value - instead, it affects the <code>height</code> property accordingly) **/
  710. override public function get scaleY():Number {
  711. return 1;
  712. }
  713. override public function set scaleY(value:Number):void {
  714. var oldScaleY:Number = _scaleY;
  715. _scaleY = value;
  716. setSize(_width, _height * (_scaleY / oldScaleY));
  717. }
  718. /** Rotation of the FlexBlitMask (always 0 because FlexBlitMasks can't be rotated!) **/
  719. override public function set rotation(value:Number):void {
  720. if (value != 0) {
  721. throw new Error("Cannot set the rotation of a FlexBlitMask to a non-zero number. FlexBlitMasks should remain unrotated.");
  722. }
  723. }
  724. /**
  725. * Typically a value between 0 and 1 indicating the <code>target's</code> position in relation to the FlexBlitMask
  726. * on the x-axis where 0 is at the beginning, 0.5 is scrolled to exactly the halfway point, and 1 is scrolled
  727. * all the way. This makes it very easy to animate the scroll. For example, to scroll from beginning to end
  728. * over 5 seconds, you could do: <br /><br /><code>
  729. *
  730. * myFlexBlitMask.scrollX = 0; <br />
  731. * TweenLite.to(myFlexBlitMask, 5, {scrollX:1});
  732. * </code>
  733. * @see #scrollY
  734. **/
  735. public function get scrollX():Number {
  736. return (super.x - _bounds.x) / (_bounds.width - _width);
  737. }
  738. public function set scrollX(value:Number):void {
  739. if (_target != null && _target.parent) {
  740. _bounds = _target.getBounds(_target.parent);
  741. var dif:Number;
  742. dif = (super.x - (_bounds.width - _width) * value) - _bounds.x;
  743. _target.x += dif;
  744. _bounds.x += dif;
  745. if (_bitmapMode) {
  746. _render();
  747. }
  748. }
  749. }
  750. /**
  751. * Typically a value between 0 and 1 indicating the <code>target's</code> position in relation to the FlexBlitMask
  752. * on the y-axis where 0 is at the beginning, 0.5 is scrolled to exactly the halfway point, and 1 is scrolled
  753. * all the way. This makes it very easy to animate the scroll. For example, to scroll from beginning to end
  754. * over 5 seconds, you could do: <br /><br /><code>
  755. *
  756. * myFlexBlitMask.scrollY = 0; <br />
  757. * TweenLite.to(myFlexBlitMask, 5, {scrollY:1});
  758. * </code>
  759. * @see #scrollX
  760. **/
  761. public function get scrollY():Number {
  762. return (super.y - _bounds.y) / (_bounds.height - _height);
  763. }
  764. public function set scrollY(value:Number):void {
  765. if (_target != null && _target.parent) {
  766. _bounds = _target.getBounds(_target.parent);
  767. var dif:Number = (super.y - (_bounds.height - _height) * value) - _bounds.y;
  768. _target.y += dif;
  769. _bounds.y += dif;
  770. if (_bitmapMode) {
  771. _render();
  772. }
  773. }
  774. }
  775. /**
  776. * If <code>false</code> (the default), the bitmap (and the FlexBlitMask's x/y coordinates)
  777. * will be rendered only on whole pixels which is faster in terms of processing. However,
  778. * for the best quality and smoothest animation, set <code>smoothing</code> to <code>true</code>.
  779. **/
  780. public function get smoothing():Boolean {
  781. return _smoothing;
  782. }
  783. public function set smoothing(value:Boolean):void {
  784. if (_smoothing != value) {
  785. _smoothing = value;
  786. _captureTargetBitmap();
  787. if (_bitmapMode) {
  788. _render();
  789. }
  790. }
  791. }
  792. /**
  793. * The ARGB hexadecimal color that should fill the empty areas of the FlexBlitMask. By default,
  794. * it is transparent (0x00000000). If you wanted a red color, for example, it would be
  795. * <code>0xFFFF0000</code>.
  796. **/
  797. public function get fillColor():uint {
  798. return _fillColor;
  799. }
  800. public function set fillColor(value:uint):void {
  801. if (_fillColor != value) {
  802. _fillColor = value;
  803. if (_bitmapMode) {
  804. _render();
  805. }
  806. }
  807. }
  808. /**
  809. * If <code>true</code>, the bitmap will be wrapped around to the opposite side when it scrolls off
  810. * one of the edges (only in <code>bitmapMode</code> of course), like the FlexBlitMask is filled with a
  811. * grid of bitmap copies of the target. Use the <code>wrapOffsetX</code> and <code>wrapOffsetY</code>
  812. * properties to affect how far apart the copies are from each other. You can reposition the
  813. * <code>target</code> anywhere and FlexBlitMask will align the copies accordingly.
  814. * @see #wrapOffsetX
  815. * @see #wrapOffsetY
  816. **/
  817. public function get wrap():Boolean {
  818. return _wrap;
  819. }
  820. public function set wrap(value:Boolean):void {
  821. if (_wrap != value) {
  822. _wrap = value;
  823. if (_bitmapMode) {
  824. _render();
  825. }
  826. }
  827. }
  828. /**
  829. * When <code>wrap</code> is <code>true</code>, <code>wrapOffsetX</code> controls how many pixels
  830. * along the x-axis the wrapped copies of the bitmap are spaced. It is essentially the gap between
  831. * the copies (although you can use a negative value or 0 to avoid any gap).
  832. * @see #wrap
  833. * @see #wrapOffsetY
  834. **/
  835. public function get wrapOffsetX():Number {
  836. return _wrapOffsetX;
  837. }
  838. public function set wrapOffsetX(value:Number):void {
  839. if (_wrapOffsetX != value) {
  840. _wrapOffsetX = value;
  841. if (_bitmapMode) {
  842. _render();
  843. }
  844. }
  845. }
  846. /**
  847. * When <code>wrap</code> is <code>true</code>, <code>wrapOffsetY</code> controls how many pixels
  848. * along the y-axis the wrapped copies of the bitmap are spaced. It is essentially the gap between
  849. * the copies (although you can use a negative value or 0 to avoid any gap).
  850. * @see #wrap
  851. * @see #wrapOffsetX
  852. **/
  853. public function get wrapOffsetY():Number {
  854. return _wrapOffsetY;
  855. }
  856. public function set wrapOffsetY(value:Number):void {
  857. if (_wrapOffsetY != value) {
  858. _wrapOffsetY = value;
  859. if (_bitmapMode) {
  860. _render();
  861. }
  862. }
  863. }
  864. }
  865. }