Monday, 26 March 2012

Radial gradient fill

I first tried using gradient fills (via the beginGradientFill method of the Graphics class) in Bug Tunnel Defense. I wanted to use them for shading along the tunnels but could never get them to work, and eventually did it the long way by drawing a series of differently coloured rectangles. The problem was the createGradientBox Matrix function, which no matter what I passed to it would never return the right matrix for a linear fill.

Over the weekend I tackled the similar but simpler problem of radial shading. It's simpler because the shading is rotationally symmetric so the angle does not come into it. But it's not described in the official documentation so I had to use trial and error to get to the right matrix.

The correct way to call createGradientBox for circles is as follows, where fX, fY and fR are the coordinates and radius of the circle. The zero is the angle which is not needed.

mat.createGradientBox(2 * fR, 2 * fR, 0, fX - fR, fY - fR);

To demonstrate it I've written a simple app, only 26 lines only ten of which do anything, available here on Wonderfl and embedded below.

No comments:

Post a Comment