Daniel
Daniel

Reputation: 7724

fast nested for to draw circle in matrix

Suppose I have a NxN matrix, where each cell is a 1x1 white square.

Suppose I have a position P and a radius R. I want to paint all the cells of the circle of radius R centered in P.

Of course I could do this:

for(int i = P.x - R; i < P.x + R; i++)
    for(int j = P.y - R; j < P.y + R; j++)
        if (distance from P to (i,j) < R)
            Paint(i,j)

But as I will run this code on a shader that will execute every frame, I'd like to know a faster way to find the correct cells instead of asking the distance for each cell, which is slow.

Is there a smarter way?

Upvotes: 2

Views: 158

Answers (1)

hbejgel
hbejgel

Reputation: 4837

You could for each given height of the circle calculate its segment width and fill it out completely.

You'd go from y = P - R to P + R filling all points in the chord (circular segment).

For the length of the chord just use formula (9) from here.

Upvotes: 2

Related Questions