/* A load manager with preloading visuals. Loads JPGs, PNGs, SWF etc to a specific MovieClip or Sprite Usage: LoadManager.add("http://blog.andrevenancio.com/wp-content/uploads/2010/02/handCursor-298x300.png", this); */ package av.utils { import flash.display.Loader; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.TimerEvent; import flash.net.URLRequest; import flash.system.LoaderContext; import flash.utils.Timer; import gs.TweenLite; public class LoadManager { /** CORE */ private static var toLoad:Array = []; private static var currentLoad:uint = 0; private static var isLoading:Boolean = false; private static var loader:Loader; private static var context:LoaderContext = new LoaderContext(); /** PRELOADER */ private static var preloader:Sprite; private static var timer:Timer = new Timer(65); public function LoadManager() { trace("This is a static class, and should not be instantiated"); } public static function add(_item:*, _target:*):void { var obj:Object = new Object(); obj.item = _item; obj.target = _target; toLoad.push(obj); if(isLoading == false)checkLoad(); } private static function checkLoad():void { if(currentLoad < toLoad.length) { isLoading = true //trace("loading item", currentLoad); loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.OPEN, onInit); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ignoreFile); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progress); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadItemComplete); context.checkPolicyFile = true; loader.load(new URLRequest(toLoad[currentLoad].item), context); } else { isLoading = false; //trace("all items loaded"); } } private static function onInit(e:Event):void { //trace("init"); preloadStart(); } private static function progress(e:ProgressEvent):void { //trace(uint((e.bytesLoaded/e.bytesTotal)*100), "%"); } private static function ignoreFile(e:IOErrorEvent):void { //trace("File:", toLoad[currentLoad].item, "not found, going on to the next one"); common(); } private static function loadItemComplete(e:Event):void { //trace("file complete"); toLoad[currentLoad].target.addChild(loader.content); common(); } private static function common():void { preloadStop(); currentLoad++ checkLoad(); } /** * PRELOADER VISUALS * * Note: The code for the "Apple logo" was taken from a class I found somewhere on the internet. I can´t find the author to give proper credits. * if you find the author, please get in touch so I can give proper credits. * */ private static function preloadStart():void { preloader = new Sprite(); preloader.alpha = 0; preloader.x = toLoad[currentLoad].target.width/2; preloader.y = toLoad[currentLoad].target.height/2; toLoad[currentLoad].target.addChild(preloader); timer.addEventListener(TimerEvent.TIMER, onTimer, false, 0, true); timer.start(); var i:int = 12; var degrees:int = 360 / 12; while (i--) { var radianAngle:Number = (degrees * i) * Math.PI / 180; var slice:Shape = getSlice(); slice.alpha = Math.max(0.2, 1 - (0.1 * i)); slice.rotation = -degrees * i; slice.x = Math.sin(radianAngle) * 6; slice.y = Math.cos(radianAngle) * 6; preloader.addChild(slice); } TweenLite.to(preloader, .5, {alpha:1}); } private static function getSlice():Shape { var slice:Shape = new Shape(); slice.graphics.beginFill(0x666666); slice.graphics.drawRoundRect(-1, 0, 2, 6, 1, 1); slice.graphics.endFill(); return slice; } private static function onTimer(e:TimerEvent):void { preloader.rotation = (preloader.rotation + (360 / 12)) % 360; } private static function preloadStop():void { timer.stop(); toLoad[currentLoad].target.removeChild(preloader); } } }
I always love to see how much the Developers put into details. I love custom mouse icons on rollover, like a close or a zoom or a grab icon. I tought I could share my way of drawing custom shapes.
Some time ago for a competition, I had the need to create custom shapes but I was restricted to not use either external images or movie clips in the library, so I decided to get my hands dirty in the graphics method once again.
At the birth of the game industry all games were basically Tile based games (you can read more in here). So, inspired by that idea I thought I could draw custom shapes using Arrays.
So the main idea is that you transform something like this:

into something like this:
![]()
With that in mind, I created a loop to check every number in the multi-arrray and based on the number, we should or shouldn´t draw something.
0 – means empty pixel
1 – means black pixel
2 – means white pixel
So, take the largely used hand cursor for example:
var hand_open:Array = [ [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 2, 2, 1, 0, 0, 0], [0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 2, 2, 1, 0, 1, 0], [0, 0, 0, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1], [0, 0, 0, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1], [0, 1, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1], [1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1], [1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0], [0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0], [0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0], [0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0], [0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0], [0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0], ]; function draw_Icon(_arr:Array):void { for (var a:uint = 0; a < _arr.length; ++a) { for (var b:uint = 0; b < _arr[a].length; ++b) { if(_arr[a][b] != 0) { _arr[a][b] == 1 ? current.graphics.beginFill(0x000000) : current.graphics.beginFill(0xFFFFFF) current.graphics.drawRect(1 * b, 1 * a, 1, 1); current.graphics.endFill(); } } } } draw_Icon(hand_open);

This icon would be great for some drag and drop kind of application. Have fun creating your custom shapes!
I wanted to create an effect for image transitions that would be similar to a glass breaking. And during my experiments I discovered some things I want to share.
Imagine your image is 400x300px and you want to divide it in 6 different parts.
You want the 1st part to be located at the 0x position, the 2nd at the 70px position and so on…
(0, 70, 100, 220, 330, 350)
So basically, your divisions over the image will be 70px for the 1st part, 30px for the 2nd and so on.
(70, 30, 120, 110, 20, 50)
And that´s it, your now able to divide a 400x300px image into 6 boring rectangles.
But, broken glass is more similar to triangles, not rectangles, so we still must divide every rectangle into 2 triangles, and this is where the fun starts.
There are no graphics.drawTriangle() methods in the graphics Class, so how can we draw triangles?
Using the graphics.moveTo() and the graphics.LineTo() methods.
The graphics.LineTo() draws a line from a given x and y coordinates to a registration point (defaults x0 y0), so, every time you want to change that registration point you must use the graphics.moveTo() method.
That said, let´s draw some triangles.
Heres how it´s done:
var W:Number = 400; var H:Number = 300; var divisions:Array = [0,70,100,220,330,350]; var sizes:Array = []; for (var j:uint =1; j<=divisions.length; ++j) { var value:Number; if (j < divisions.length) { value = divisions[j] - divisions[j - 1]; } else { value = W - divisions[j - 1]; } sizes.push(value); } for (var i:uint = 0; i<divisions.length; ++i) { drawTriangles(divisions[i], sizes[i], H); } function drawTriangles(mX:Number, sizeW:Number, H:Number):void { graphics.beginFill(Math.random()*0xFF0000); graphics.moveTo(mX,0); graphics.lineTo(mX + sizeW,0); graphics.lineTo(mX + sizeW,H); graphics.beginFill(Math.random()*0x00FF00); graphics.moveTo(mX,0); graphics.lineTo(mX + 0,H); graphics.lineTo(mX + sizeW,H); }
With a bit of imagination, you can see glass somewhere… Hopefully!
You can download the source here.
So I have to do a calendar and implement it on an AS3 website? No problem! (I thought!…) Where the hell is the calendar component that we had in AS2? And why couldn´t I find a way to use the one in Flex?
Enough with the questions, here are some answers.
Document Class
package { import com.andrevenancio.component.Calendar; import flash.display.Sprite; public class Main extends Sprite { private var calendar:Calendar; public function Main() { calendar = new Calendar(); calendar.x = 50; calendar.y = 50; addChild(calendar); var _data:Date = new Date(); calendar.month = _data.getMonth(); calendar.year = _data.getFullYear(); calendar.Render(); } } }
And here is the Calendar Class
package com.andrevenancio.component { import flash.display.Sprite; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFormat; public class Calendar extends Sprite { /** TEXT FORMAT */ private var month_tf:TextFormat; private var week_tf:TextFormat; private var days_tf:TextFormat; private var button_tf:TextFormat; /** LANGUAGE CONFIG */ private var _months:Array = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] private var _days:Array = ["S", "M", "T", "W", "T", "F", "S"] /** DAYS PER MONTH */ private var _monthTotal:Array = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); /** CALENDAR */ private var _today:Date = new Date(); private var _targetMonth:uint = _today.getMonth(); private var _targetYear:uint = _today.getFullYear(); /** VISUAL ASSETS */ private var _selectedMonth:TextField; private var _daysWeek:Sprite = new Sprite(); private var _nextBT:Sprite = new Sprite(); private var _prevBT:Sprite = new Sprite(); /** HOLDER FOR DAYS OF THE MONTH */ private var _holder:Sprite = new Sprite(); public function Calendar() { configStyle(); build(); } /** * Style Configurations * */ private function configStyle():void { month_tf = new TextFormat("Arial", 14, 0x333333, true); month_tf.align = "center"; week_tf = new TextFormat("Arial", 10, 0x666666, true); week_tf.align = "center"; days_tf = new TextFormat("Arial", 10, 0x666666); days_tf.align = "center"; button_tf = new TextFormat("Arial", 10, 0xFFFFFF); button_tf.align = "center"; } /** * Builds interface * */ private function build():void { /** Month and Year TextField */ _selectedMonth = new TextField(); _selectedMonth.text = ""; _selectedMonth.border = _selectedMonth.selectable = false; _selectedMonth.width = 140; _selectedMonth.height = 20; _selectedMonth.defaultTextFormat = TextFormat(month_tf); addChild(_selectedMonth); /** Days of the week */ addChild(_daysWeek); for(var i:uint = 0; i<7;++i) { var temp:Sprite = new Sprite(); temp.graphics.beginFill(0,0); temp.graphics.drawRect(0,0, 20, 20); temp.graphics.endFill(); temp.x = 20 * i; temp.y = _selectedMonth.y + _selectedMonth.height; addChild(temp); writeText(_days[i], week_tf, temp); } /** Buttons */ _prevBT.graphics.beginFill(1); _prevBT.graphics.drawRect(0, 0, 16, 16); _prevBT.graphics.endFill(); _nextBT.graphics.beginFill(0); _nextBT.graphics.drawRect(0, 0, 16, 16); _nextBT.graphics.endFill(); addChild(_prevBT); addChild(_nextBT); writeText("<<", button_tf, _prevBT); writeText(">>", button_tf, _nextBT); _prevBT.x = -_prevBT.width; _prevBT.y = 5; _nextBT.x = _selectedMonth.width; _nextBT.y = 5; _nextBT.buttonMode = _prevBT.buttonMode = true; _prevBT.addEventListener(MouseEvent.CLICK, prevMonth); _nextBT.addEventListener(MouseEvent.CLICK, nextMonth); /** Holder for days of the month */ addChild(_holder); _holder.y = _selectedMonth.y + _selectedMonth.height; } /** * decreases current month and year if necessary * */ private function prevMonth(e:MouseEvent):void { _targetMonth = _targetMonth == 0 ? 12 : _targetMonth % 12; _targetMonth-- _targetMonth % 12 == 11 ? _targetYear-- : null; Render(); } /** * increments current month and year if necessary * */ private function nextMonth(e:MouseEvent):void { _targetMonth++ _targetMonth = _targetMonth == 12 ? 0 : _targetMonth % 12; _targetMonth % 12 == 0 ? _targetYear++ : null; Render(); } /** * Write text in some sprite * */ private function writeText(_text:String, _textFormat:TextFormat, _target:Sprite):void { var label_txt:TextField = new TextField(); label_txt.text = _text; label_txt.border = label_txt.selectable = label_txt.mouseEnabled = false; label_txt.autoSize = "left"; label_txt.defaultTextFormat = TextFormat(_textFormat); label_txt.setTextFormat(_textFormat); _target.addChild(label_txt); } /** * Remove all days of the month (sprites). * */ private function cleanGraphics():void { var total:uint = _holder.numChildren; for(var i:uint = 0; i < total;++i) { _holder.removeChildAt(0); } } /** * Renders Calendar info * */ public function Render():void { /** removes all unnecessary assets */ cleanGraphics(); /** changes calendar month and year */ _selectedMonth.text = _months[_targetMonth % 12] + " " + _targetYear; /** draws calendar based on year and month */ var daysNo:uint = (_targetYear % 4 == 0 && _targetMonth % 12 == 1 ? 29 : _monthTotal[_targetMonth % 12]); /** gets 1st day of the week in current selected month */ var temp:Date = new Date(_targetYear, _targetMonth); var startDay:uint = temp.getDay(); /** Adds sprite with days */ var row:Number = 0; for (var i:uint = 1; i < daysNo+1; i++) { var sp:Sprite = new Sprite(); sp.x = startDay * 20; sp.y = (row+1) * 20; _holder.addChild(sp); writeText(i.toString(), days_tf, sp); startDay++; /** changes row on saturdays */ if(startDay >= 7) { startDay = 0; row++; } } } /** * SETTERS GETTERS * */ public function set month(_value:uint):void {_targetMonth = _value;} public function set year(_value:uint):void {_targetYear = _value;} public function get month():uint {return _targetMonth;} public function get year():uint {return _targetYear;} } }
I have created some setters and getters, because in my case I wanted to call a Zend AMF Service that returned all the events for the specified month.
You can download the source here.
In this example I´m downloading 2 images and merging them into 1.
Image 1

Image 2

var bd1:BitmapData; var bd2:BitmapData; loadImage("http://blog.andrevenancio.com/wp-content/uploads/2010/01/icecream.png"); function loadImage(url:String):void { var _request:URLRequest = new URLRequest(url); var _loader:Loader = new Loader(); var _context:LoaderContext = new LoaderContext(); _context.checkPolicyFile = true; _loader.load(_request, _context); _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); } function loadComplete(e:Event):void { if (bd1 == null && bd2 == null) { bd1 = Bitmap(e.target.content).bitmapData; trace(bd1.width, bd1.height); loadImage("http://blog.andrevenancio.com/wp-content/uploads/2010/01/watermark.png"); } else if (bd1 !=null && bd2 == null) { bd2 = Bitmap(e.target.content).bitmapData; allImagesAreLoaded(); } } function allImagesAreLoaded():void { var bm:Bitmap = new Bitmap(); addChild(bm); bm.bitmapData = mergeBitmap(bd1, bd2); } function mergeBitmap(_data1:BitmapData, _data2:BitmapData):BitmapData { var mergedData:BitmapData = _data1; mergedData.draw(_data2); return mergedData; }
The RegExp class lets you work with regular expressions, which are patterns that you can use to perform searches in strings and to replace text in strings.
trace(testRegex("some@email.com")); //returns true trace(testRegex("some.com"));//returns false function testRegex(_input:String):Boolean { var validEmailRegExp:RegExp = /([a-z0-9._-]+)@([a-z0-9.-]+)\.([a-z]{2,4})/; switch (String(validEmailRegExp.test(_input)).toLowerCase()) { case "true": return true; break; default: return false break; } }
Sometimes you want to load images from another server. If that´s true, you need to check for a policy file, otherwise you can´t get the data from the file, and you will get a sandbox violation error:
“SecurityError: Error #2122: Security sandbox violation: Loader.content: http://yoursite cannot access http://targetsite
A policy file is required, but the checkPolicyFile flag was not set when this media was loaded.”
(…)
We´ll be using the LoaderContext() method to check for the policy file.
package { import flash.display.Bitmap; import flash.display.Loader; import flash.display.Sprite; import flash.events.Event; import flash.net.URLRequest; import flash.system.LoaderContext; public class Main extends Sprite { private var request:URLRequest; private var loader:Loader; private var context:LoaderContext; public function Main() { request = new URLRequest("http://www.google.pt/intl/en_com/images/logo_plain.png"); loader = new Loader(); context = new LoaderContext(); context.checkPolicyFile = true; loader.load(request, context); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, load_complete); } private function load_complete(e:Event):void { var bitmap:Bitmap = loader.content as Bitmap; bitmap.smoothing = true; addChild(bitmap); } } }
Just another way to trigger events based on time like setInterval() or setTimeout().
The Timer class is the interface to timers, which let you run code on a specified time sequence. Use the start() method to start a timer. Add an event listener for the timer event to set up code to be run on the timer interval.
//500 is the delay interval in ms, 3 means it should repeat three times. //Leave only the 500 if you want to repeat endlessly. var _timer:Timer = new Timer(500, 3); _timer.addEventListener(TimerEvent.TIMER, _onTimer); _timer.start(); function _onTimer(e:TimerEvent):void { trace("Delay: " + e.currentTarget.delay, ". Fired: " + e.currentTarget.currentCount + " times." ); }
With Flash 10, we can easily change cursors with the flash.ui.MouseCursor Class.
This is a simple example with all the available cursors. Read more about it here .
I´ve created a Sprite with MouseEvents as otherwise the cursors will change even if your mouse is not over the SWF. I’ve got to be honest, I don´t find this very helpful. I appreciate any comments, because I really don´t see the point of the cursor not changing back to “normal” if your mouse is not over the SWF. Hope this can be fixed soon.
package { import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.ui.Mouse; import flash.ui.MouseCursor; import flash.utils.Timer; public class Main extends Sprite { private var _stage:Sprite = new Sprite(); private var _current:uint = 0; private var cursors:Array = [MouseCursor.ARROW, MouseCursor.BUTTON, MouseCursor.HAND, MouseCursor.IBEAM]; private var _timer:Timer; public function Main() { addChild(_stage); _stage.graphics.beginFill(0, 0); _stage.graphics.drawRect(0, 0, 400, 300); _stage.graphics.endFill(); _timer = new Timer(200); _timer.addEventListener(TimerEvent.TIMER, doMouseChange); _stage.addEventListener(MouseEvent.MOUSE_OVER, onOver); _stage.addEventListener(MouseEvent.MOUSE_OUT, onLeave); } private function onOver(e:MouseEvent):void { _timer.start(); } private function onLeave(e:MouseEvent):void { _timer.stop(); Mouse.cursor = cursors[0]; } private function doMouseChange(e:TimerEvent):void { Mouse.cursor = cursors[_current % cursors.length]; ++_current; } } }
You can download the source here.
This is a common method I use to return a value (Number or int) between a minimum and a maximum.
trace(randRange(-9, 9, true)); function randRange(min:int, max:int, _int:Boolean = true) { return _int == false ? Math.random()*(max-min)+min : int(Math.random()*(max-min)+min); }
What the hell is that?
That´s basically an if statement.
condition ? isTrue : isFalse;
return _int == false ? Math.random()*(max-min)+min : int(Math.random()*(max-min)+min);
//these are the formulas //If the _int == false Math.random()*(max-min)+min; //If the _int == true int(Math.random()*(max-min)+min);



