Friday, 2 March 2012

Drawing a pie chart

This is something I wrote for the game I'm working on but removed a few days ago as I went in a different direction in the design. As the code is fairly self-contained I thought it might be of interest.

The code generates a pie chart, entirely in code, though it could be easily used with art. It's designed to be dynamic so the chart can be re-drawn any time. Each chart is a BitmapData so easily added to the stage or drawn into another BitmapData.

The drawing is in two stages. It initially draws a circle, with a border, in the function Make(). This could be replaced with better drawing commands or art created beforehand. It uses the technique described here to generate an alpha channel.

Then in the Update() function, which must be called at least once, it creates a mask to cut out a segment or slice, the size of which depends on the parameter passed in. The mask is a simple polygon, with edges that either coincide with the bounds of the BitmapData or with the sides of the slice.

The last line uses BitmapData.draw() with the polygon used as a mask on the circle to produce the final pie chart. The BitmapData inputs can be reversed, producing a graph that uses the pixels of the polygon rather than the circle.

The code is on Wonderfl here or via the embed below: it's rather a lot of code so was easier to put there than formatted in this post.

No comments:

Post a comment