Index Books FAQ Contact About Rod

# Title: Calculate the formula for a circle selected by the user in C#

This example shows how to calculate the formula for a circle that the user has selected by clicking and dragging. The program uses the usual MouseDown, MouseMove, and MouseUp event handlers to let the user draw the circle. The only trick is that it makes the width and height of the object it draws the same, so the result is a circle and not an ellipse.

The following code shows the part of the form's Paint event handler that draws a new circle while the user is selecting it.

// Draw the new circle if we are drawing one. if (DrawingCircle) { // Make it a circle. int diameter = Math.Max( Math.Abs(StartX - EndX), Math.Abs(StartY - EndY)); e.Graphics.DrawEllipse(Pens.Red, Math.Min(StartX, EndX), Math.Min(StartY, EndY), diameter, diameter); }

Here StartX and StartY are the coordinates of the point where the user pressed the mouse down. The values EndX and EndY are the mouse's current location during the click-and-drag.

This code uses the maximum of the selected area's width and height as the circle's diameter. It uses the minimum X and Y coordinates of the selected area as the upper left corner for the circle and draws the circle.

The rest of the code that selects a circle is fairly straightforward. Download the example to see the details.

The more interesting code is in the following GetCircleFormula method.

// Get the equation for this circle. private void GetCircleFormula(RectangleF rect, out float dx, out float dy, out float r) { dx = rect.X + rect.Width / 2f; dy = rect.Y + rect.Height / 2f; r = rect.Width / 2f; }

As its name implies, this method calculates the circle's formula. The figure to the right shows the geometry of a circle.

The GetCircleFormula method finds the center of the circle (Dx, Dy). It divides the circle's width by 2 to get the radius.

Now the program can display the equation in a Label.
Sometimes it's convenient to use another type of equation for a circle. Using the equations on the left, you can solve the original equation to make an equation giving y as a function of x.

Note that taking the square root means there are two possible solutions to the equation, one where you take the positive root and one where you take the negative root. The positive and negative roots give the upper and lower halves of the circle.

The following code shows how the program draws the circle after the user selects it. (This technique is really just used to show that we have the right equation and to show one method for drawing a circle. Using the Graphics object's DrawEllipse method is much more efficient.)