Search code examples
graphics2d

draw a circle within a square while dragging a mouse


I'm not having a good day I think, and I'm struggling with an issue I think it should be easy.

I have to draw a circle while dragging the mouse. The users clicks and holds, drags the mouse, and release the button.

But:

1) I have the coordinates of the mousedown event, and the current ones (x1, y1, x2, y2). This ones defines a rectangle.

2) (x1, y1) must be the center of the circle, and it radius must be the distance between x1, y1 and the current ones.

3) I have to show the current radius (the value; not the line itself).

4) The user must be able to draw the circle dragging left, right, upwards, downwards, and any intermediate combination.

Thank you very much!

PS: As an option (example, if the user drags while shift key is pressed), the rectangle should be a square and a circle should be drawn instead of an oval.


Solution

  • (wagering that 0,0 is left upper corner otherwise invert 1 and 2; x1/y1 is buttondown is center)

    radius = sqrt((x1-x2)^2 + (y1-y2)^2)

    x_leftuppercorner = x1 - radius

    y_leftuppercorner = y1 - radius

    x_rightlowercorner = x1 + radius

    y_rightlowercorner = y1 + radius

    dCircle(x_luc, y_luc, x_ruc, y_ruc)