Search code examples
c#winformsgraphics2dgraphicspath

Adding an arc to a rectangle using GraphicsPath


I am trying to draw a top view of an IC package, which should look like this (sorry I couldnt even draw it good enough using windows's paint!)

enter image description here

I am using a path obeject, but the result of my path object is no where near what I expect. Atleast the complete rectangle itself draws fine but I have problem to make that top arc you see in my example picture. Would be nice if you can point me to the right place. Here is my code:

    private GraphicsPath DrawDilBounds(Size size)
    {
        var p = new GraphicsPath(FillMode.Alternate);
        p.StartFigure();
        p.AddLine(0, 0, 0, size.Height);
        p.AddLine(0, size.Height, size.Width, size.Height);
        p.AddLine(size.Width, size.Height, size.Width, 0);
        p.AddLine(size.Width, 0, (size.Width/2) - 10, 0);
        p.AddArc(size.Width/2 - 10, 0, 10, 10, 10, 10); //This arc looks like no arc!
        p.AddLine((size.Width/2) + 10, 0, 0, 0);
        p.CloseFigure();

        return p;
    }

So what I am doing here is starting some lines from top left corner , to bottom left corner, to right bottom corner and finaly to top right corner, then I added a line from top right corner to the middle of the top , minus 10 pixels then I want to add the arc with width of 20 pixels and then finish the drawing back to the top left corner.


Solution

  • You specify the arc by its bounding box. Using 10 as the radius gives a box of 20 x 20 (you used 10 x 10) whose upper left corner is located at (-10, -10) from the center of the arc (you used (-10, 0)). The last two arguments must be degrees, the starting and ending angle. Since you draw it from left-to-right that will be 0 and 180 degrees (you used 10 and 10). You also fumbled the lengths of the 2 lines at the top, they should be half the width -10 (you used +10). Fix:

            p.AddLine(size.Width, 0, (size.Width / 2) + 10, 0);
            p.AddArc(size.Width / 2 - 10, -10, 20, 20, 0, 180);
            p.AddLine((size.Width / 2) - 10, 0, 0, 0);
    

    Which gets you:

    enter image description here