Pie mask in AS3

Sometimes 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.

Get Adobe Flash player

You can get the example fla here.

Tags: , , , , ,

4 Responses to “Pie mask in AS3”

  1. Nizzle Says:

    Do you actually know all that Math right from the top of your head? I have no idea how that works, but I thinks it is amazing.

  2. Flassari Says:

    Thanks Nizzle,
    in this case I knew most of the math beforehand (I like trigonometry) except for the line where I increase the length of the radius, but for that I had to check my trigonometry cheat sheet =)
    I also don’t just code it directly, I scribble it down on some post-it notes first to get the formulas out of my head.
    I hope the function came to good use for you.

  3. puha Says:

    Thanks. The .fla isn’t in the zip file, only the swf.

  4. Flassari Says:

    Oops, thanks for spotting that, I zipped the wrong file.
    I uploaded the right one, you might have to clear your cache to get the new one.

Leave a Reply

Spam protection by WP Captcha-Free