Graphics.FillPath()的问题行为

本文关键字:问题 FillPath Graphics | 更新日期: 2023-09-27 18:26:23

我创建了一个小函数,用于绘制边缘更细的矩形。(你可以称之为圆角矩形)

以下是我的操作方法:

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);
}

下面是调用以下函数的Paint事件处理程序:

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

运行它,确实会得到想要的结果,这就是:

一个如我所愿的好结果。

但是,如果我更改
G.DrawPath(Pens.Blue,GP);
行:
G.FillPath(Brushes.Blue,GP);
那么我得到的是:

不是我想要的结果
矩形的底部是尖锐的,并且不像DrawPath()方法那样根据需要进行圆角处理。

有人知道我应该怎么做才能让FillPath()方法也能正常工作吗
如果重要的话,我使用的是.NET Framework 2.0。

Graphics.FillPath()的问题行为

如果你想要一个真正的取整的rect实现,你应该使用评论者blas3nik引用的问题中的代码,位于Graphics.FillPath.的奇数绘制的GraphicsPath

您的实现主要只是移除四个角上的每个像素。因此,不需要使用GraphicsPath来绘制此图。只需填充几个重叠的矩形,将这些像素排除在外:

    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);
    }