Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problematic Behavior of Graphics.FillPath()

Tags:

c#

gdi+

I created a small function that draws a Rectangle with finer edges. (you can call it a rounded rectangle)

Here is how I do it:

private void    DrawRoundedRectangle(Graphics G, int X1, int Y1, int X2, int Y2)
{
    GraphicsPath    GP  =new GraphicsPath();
    GP.AddLine(X1+1,Y1  ,  X2-1,Y1  );
    GP.AddLine(X2-1,Y1  ,  X2  ,Y1+1);
    GP.AddLine(X2  ,Y1+1,  X2  ,Y2-1);
    GP.AddLine(X2  ,Y2-1,  X2-1,Y2  );
    GP.AddLine(X2-1,Y2  ,  X1+1,Y2  );
    GP.AddLine(X1+1,Y2  ,  X1  ,Y2-1);
    GP.AddLine(X1  ,Y2-1,  X1  ,Y1+1);
    GP.AddLine(X1  ,Y1+1,  X1+1,Y1  );

    G.DrawPath(Pens.Blue,GP);
}

And here is the Paint event handler that calls this function:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    this.DrawRoundedRectangle(e.Graphics,50,50,60,55);
}

Running it, indeed gives the desired result, which is this:

A good result as I wished.

However If I change the
G.DrawPath(Pens.Blue,GP);
line to be:
G.FillPath(Brushes.Blue,GP);
then what I get is this:

Not the result I wanted..
The bottom part of the rectangle is sharp, and not rounded as needed, like it was with the DrawPath() method.

Anyone knows what I should do to make the FillPath() method work well too?
If It matters, I am using .NET Framework 2.0.

like image 206
spaceman Avatar asked Mar 09 '26 00:03

spaceman


1 Answers

If you want a real rounded-rect implementation, you should use the code in the question referenced by commenter blas3nik, at Oddly drawn GraphicsPath with Graphics.FillPath.

Your implementation mainly just removes each of the pixels at the four corners. As such, there's no need to use GraphicsPath to draw this. Just fill a couple of overlapping rectangles that exclude those pixels:

    private void FillRoundedRectangle(Graphics G, int X1, int Y1, int X2, int Y2)
    {
        int width = X2 - X1, height = Y2 - Y1;

        G.FillRectangle(Brushes.Blue, X1 + 1, Y1, width - 2, height);
        G.FillRectangle(Brushes.Blue, X1, Y1 + 1, width, height - 2);
    }
like image 77
Peter Duniho Avatar answered Mar 10 '26 13:03

Peter Duniho