On SO, found the following simple algorithm for drawing filled circles:
for(int y=-radius; y<=radius; y++)
for(int x=-radius; x<=radius; x++)
if(x*x+y*y <= radius*radius)
setpixel(origin.x+x, origin.y+y);
Is there an equally simple algorithm for drawing filled ellipses?
Simpler, with no
doubleand no division (but be careful of integer overflow):We can take advantage of two facts to optimize this significantly:
The first fact saves three-quarters of the work (almost); the second fact tremendously reduces the number of tests (we test only along the edge of the ellipse, and even there we don’t have to test every point).
This works because each scan line is shorter than the previous one, by at least as much
as that one was shorter than the one before it. Because of rounding to integer pixel coordinates, that’s not perfectly accurate — the line can be shorter by one pixel less that that.
In other words, starting from the longest scan line (the horizontal diameter), the amount by which each line is shorter than the previous one, denoted
dxin the code, decreases by at most one, stays the same, or increases. The first innerforfinds the exact amount by which the current scan line is shorter than the previous one, starting atdx - 1and up, until we land just inside the ellipse.To compare the number of inside-ellipse tests, each asterisk is one pair of coordinates tested in the naive version:
… and in the improved version: