Pie mask in AS3
Friday, November 13th, 2009Sometimes I have the need for a rotational progress bar that acts like a pie growing bigger (or smaller if that strikes your fancy). As usual, I made my own =)
The function drawPieMask takes first the graphics object of the displayObject instance and draws a part of pie on it, percentage set’s how big the part is.
If you want to offset the rotation of the pie (it starts to the right by default) you can set the rotation parameter. Note that rotation is in radians, not degrees, but you can multiply your degrees by (Math.PI/180) to convert to radians.
Lastly, the sides property determines how many sides the circle drawn in the mask has. You can see an example of different pie masks after the code.
To make the code as customizable as possible, it does not make a call to beginFill in case you want to set your own fill (or gradientfill even?).
If you just want to use it as a basic mask, just call beginFill(0) before and endFill() after the call to drawPieMask.
function drawPieMask(graphics:Graphics, percentage:Number, radius:Number = 50, x:Number = 0, y:Number = 0, rotation:Number = 0, sides:int = 6):void { // graphics should have its beginFill function already called by now graphics.moveTo(x, y); if (sides < 3) sides = 3; // 3 sides minimum // Increase the length of the radius to cover the whole target radius /= Math.cos(1/sides * Math.PI); // Shortcut function var lineToRadians:Function = function(rads:Number):void { graphics.lineTo(Math.cos(rads) * radius + x, Math.sin(rads) * radius + y); }; // Find how many sides we have to draw var sidesToDraw:int = Math.floor(percentage * sides); for (var i:int = 0; i <= sidesToDraw; i++) lineToRadians((i / sides) * (Math.PI * 2) + rotation); // Draw the last fractioned side if (percentage * sides != sidesToDraw) lineToRadians(percentage * (Math.PI * 2) + rotation); }
Example of different sides values. The last circle has a pie with 3 sides as a mask.
You can get the example fla here.