之前看到某度搜出的相关文章,照着去实现,发现全都是有问题的写法,没有经过验证,基本上都是复制黏贴而来,非常误导人。这里我贴出自己实践后的代码,以供需要之人参考使用。
//本段的代码是写在OnPaint方法里,在其他方法中的写法可能会有所不同,但思路一样
//x,y是矩形左上角的坐标点(起始点),width是矩形的宽度,height是矩形的长度,radius是圆角半径
var pen = new Pen(Border, 1) // Border指代边线的颜色,如Color.Red
{
DashStyle = DashStyle.Solid
};
var gp = new GraphicsPath();
gp.StartFigure();
//上边
gp.AddLine(new PointF(x + Radius / 2, y), new PointF(x + width - Radius / 2, y));
//右上角
gp.AddArc(new Rectangle(x + width - Radius, y, Radius, Radius), 270, 90);
//右边
gp.AddLine(new PointF(x + width, y + Radius / 2), new PointF(x + width, y + height - Radius / 2));
//右下角
gp.AddArc(new Rectangle(x + width - Radius, y + height - Radius, Radius, Radius), 0, 90);
//下边
gp.AddLine(new PointF(x + Radius / 2, y + height), new PointF(x + width - Radius / 2, y + height));
//左下角
gp.AddArc(new Rectangle(x, y + height - Radius, Radius, Radius), 90, 90);
//左边
gp.AddLine(new PointF(x, y + Radius / 2), new PointF(x, y + height - Radius / 2));
//左上角
gp.AddArc(new Rectangle(x, y, Radius, Radius), 180, 90);
gp.CloseFigure();
e.Graphics.DrawPath(pen, gp); // e是PaintEventArgs
在用GraphicsPath画圆角矩形时,要特别注意一点,就是矩形的画法要按照一笔画的顺序依次实现,最终图形闭合。如上面代码所示,画矩形的顺序是上边—>右上角—>右边—>右下角—>下边—>左下角—>左边—>左上角。如果不按照这种方式来,画出的图形就会线条纵横。这一点非常重要,切记!
效果图:
![]()
实践出真知:绘制圆角矩形的正确代码示例
本文作者分享了在实践中遇到的关于使用GraphicsPath绘制圆角矩形的问题,指出网络上很多教程的错误,并提供了经过验证的正确代码。代码详细解释了绘制顺序的重要性,强调必须按照特定顺序进行,否则会导致图形线条错乱。附带了实际运行效果截图,为需要此功能的开发者提供可靠参考。
8593

被折叠的 条评论
为什么被折叠?



