我编写了一些GraphicsPath
基于自定义结构创建圆角矩形的代码BorderRadius
(它允许我定义矩形的左上角、右上角、左下角和右下角半径)和初始值Rectangle
本身:
public static GraphicsPath CreateRoundRectanglePath(BorderRadius radius, Rectangle rectangle)
{
GraphicsPath result = new GraphicsPath();
if (radius.TopLeft > 0)
{
result.AddArc(rectangle.X, rectangle.Y, radius.TopLeft, radius.TopLeft, 180, 90);
}
else
{
result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y), new System.Drawing.Point(rectangle.X, rectangle.Y));
}
if (radius.TopRight > 0)
{
result.AddArc(rectangle.X + rectangle.Width - radius.TopRight, rectangle.Y, radius.TopRight, radius.TopRight, 270, 90);
}
else
{
result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y));
}
if (radius.BottomRight > 0)
{
result.AddArc(rectangle.X + rectangle.Width - radius.BottomRight, rectangle.Y + rectangle.Height - radius.BottomRight, radius.BottomRight, radius.BottomRight, 0, 90);
}
else
{
result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height));
}
if (radius.BottomLeft > 0)
{
result.AddArc(rectangle.X, rectangle.Y + rectangle.Height - radius.BottomLeft, radius.BottomLeft, radius.BottomLeft, 90, 90);
}
else
{
result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height));
}
return result;
}
现在,如果我将它与 FillPath 和 DrawPath 一起使用,我会注意到一些奇怪的结果:
GraphicsPath path = CreateRoundRectanglePath(new BorderRadius(8), new Rectangle(10, 10, 100, 100));
e.Graphics.DrawPath(new Pen(Color.Black, 1), path);
e.Graphics.FillPath(new SolidBrush(Color.Black), path);
我放大了每个结果Rectangle
(右侧),以便您可以清楚地看到问题:
我想知道的是:为什么绘制矩形上的所有弧都相等,而填充矩形上的所有弧都是奇数?
更好的是,可以修复它,以便正确绘制填充的矩形吗?
编辑:是否可以在不使用 FillPath 的情况下填充 GraphicsPath 的内部?
编辑:根据评论....这里是 BorderRadius 结构的一个例子
public struct BorderRadius
{
public Int32 TopLeft { get; set; }
public Int32 TopRight { get; set; }
public Int32 BottomLeft { get; set; }
public Int32 BottomRight { get; set; }
public BorderRadius(int all) : this()
{
this.TopLeft = this.TopRight = this.BottomLeft = this.BottomRight = all;
}
}