C#绘制带圆角的矩形
时间: 2025-02-07 19:25:53 浏览: 24
C# 中绘制带圆角的矩形
在 C# 中可以通过 System.Drawing
命名空间中的类来实现带有圆角的矩形绘制。下面是一个简单的例子,展示了如何创建并绘制一个具有指定半径圆角的矩形。
using System;
using System.Drawing;
using System.Windows.Forms;
public class RoundedRectForm : Form {
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Black);
Rectangle rect = new Rectangle(50, 50, 200, 100);
int cornerRadius = 20; // 圆角度数
using (GraphicsPath path = GetRoundedRectangle(rect, cornerRadius)) {
g.DrawPath(pen, path); // 绘制路径即为圆角矩形
}
}
private static GraphicsPath GetRoundedRectangle(Rectangle bounds, int radius) {
var path = new GraphicsPath();
if (radius <= 0 || Math.Min(bounds.Width, bounds.Height) / 2 < radius) {
path.AddRectangle(bounds);
path.CloseFigure();
return path;
} else {
Size size = new Size(radius, radius);
Point topLeft = new Point(bounds.Left, bounds.Top);
Point topRight = new Point(bounds.Right - radius, bounds.Top);
Point bottomLeft = new Point(bounds.Left, bounds.Bottom - radius);
Point bottomRight = new Point(bounds.Right - radius, bounds.Bottom - radius);
path.AddArc(new Rectangle(topLeft, size), 180, 90);
path.AddLine(new Point(bounds.Left + radius, bounds.Top), new Point(bounds.Right - radius, bounds.Top));
path.AddArc(new Rectangle(topRight.X, topLeft.Y, size.Width, size.Height), 270, 90);
path.AddLine(new Point(bounds.Right, bounds.Top + radius), new Point(bounds.Right, bounds.Bottom - radius));
path.AddArc(new Rectangle(bottomRight.X, bottomRight.Y-size.Height, size.Width, size.Height), 0, 90);
path.AddLine(new Point(bounds.Right - radius, bounds.Bottom), new Point(bounds.Left + radius, bounds.Bottom));
path.AddArc(new Rectangle(bottomLeft.X, bottomLeft.Y-radius, size.Width, size.Height), 90, 90);
path.CloseFigure();
return path;
}
}
}
此代码定义了一个自定义窗体 (RoundedRectForm
) 并重写了其 OnPaint
方法,在该方法内使用了 GetRoundedRectangle()
函数生成一个圆形角落的图形路径,并通过调用 g.DrawPath()
来实际渲染这个形状到屏幕上[^1]。
相关推荐



















