Search code examples
c#system.drawing

c# drawing library calculate ranges and midpoints to draw and circle


Basically i have a menu that user choose the shape wanted to be drawn, then the user click on two points, between those two points the chosen shape will be drawn.
I did the Square which is calculated this way

// calculate ranges and mid points
xDiff = oppPt.X - keyPt.X;
yDiff = oppPt.Y - keyPt.Y;
xMid = (oppPt.X + keyPt.X) / 2;
yMid = (oppPt.Y + keyPt.Y) / 2;

// draw square
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y,
    (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2));
g.DrawLine(blackPen, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2),
    (int)oppPt.X, (int)oppPt.Y);
g.DrawLine(blackPen, (int)oppPt.X, (int)oppPt.Y,
    (int)(xMid - yDiff / 2), (int)(yMid + xDiff / 2));
g.DrawLine(blackPen, (int)(xMid - yDiff / 2),
    (int)(yMid + xDiff / 2), (int)keyPt.X, (int)keyPt.Y);

but i can't figure out how to draw the circle and the triangle the same way

Please advise, thanks


Solution

  • On Same Way.

    int left = 20, top = 20
    int right = 100, bot = 100;
    
    // triangle
    g.DrawLine(Pens.Red, left, bot, right, bot);
    g.DrawLine(Pens.Red, right, bot, left + (right-left) / 2 /* was miss calc */, top);
    g.DrawLine(Pens.Red, left + (right - left) / 2, top, left, bot);  // better looks
    //g.DrawLine(Pens.Red, left, bot, left + (right-left) / 2 /* was miss calc */, top);
    
    // circle
    int len = (right - left) / 2;
    int centerX = left + (right - left) / 2, centerY = top + (bot - top) / 2;
    for (int i = 0; i <= 360; i++)
    {
        int degrees = i;
        double radians = degrees * (Math.PI / 180);
    
        int x = centerX + (int)(len * Math.Cos(radians));
        int y = centerY + (int)(len * Math.Sin(radians));
        e.Graphics.FillRectangle(Brushes.Red, x, y, 1, 1); // single pixel drawing
    }
    

    But Ellipse is more difficult

    http://www.petercollingridge.co.uk/tutorials/computational-geometry/finding-angle-around-ellipse/

    Upper link is help for Ellipse