Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the coordinates in a circle

Tags:

c#

math

wpf

I am drawing an imaginary circle around the middle of a button.

The radius of the circle is the Height/2 if Height>Width or Width/2 if Width>Height. Now i have to calculate which coordinates (in pixels) are in this circle. The idea is that if e.g. the mouse cursor hovers over that circle, something happens.

like image 540
Tim T Avatar asked Nov 22 '25 03:11

Tim T


2 Answers

Calculating each co-ordinate is overkill; just compare the distance to the center. For example:

int radius = 5; // whatever

int deltaX = originX - mouseX, deltaY = originY - mouseY;

// compare the square distance, to avoid an unnecessary square-root
if((deltaX * deltaX) + (deltaY * deltaY) <= (radius * radius)) {
    // inside the circle, or on the edge
}

To avoid a little math, you could also do a quick bounding-box check, i.e. checking the rectangular region (just addition/subtraction). This can be used in combination, i.e.

  • check the bounding box
    • if it isn't in the bounding box it certainly isn't in the circle
    • if it is in the bounding box, do the math to compare the square-distance
like image 162
Marc Gravell Avatar answered Nov 24 '25 17:11

Marc Gravell


You are inside the circle when this equation is satisfied:

Math.pow(mouse_pos_x-center_circle_x,2)+Math.pow(mouse_pos_y-center_circle_y,2)<Math.pow(radius,2)
like image 31
melopsitaco Avatar answered Nov 24 '25 17:11

melopsitaco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!