C# 创建 圆角 button
时间: 2023-07-12 18:07:56 浏览: 249
C#圆角按钮
4星 · 用户满意度95%
要创建圆角 button,可以使用 C# 的 System.Windows.Forms 命名空间中的 Button 控件,并设置其 FlatStyle 属性为 FlatStyle.Flat,同时设置其 FlatAppearance 属性中的 BorderSize 和 CornerRadius 属性来实现圆角效果。
下面是一个示例代码:
```
using System.Drawing;
using System.Windows.Forms;
public class RoundButton : Button
{
public RoundButton()
{
this.FlatStyle = FlatStyle.Flat;
this.FlatAppearance.BorderSize = 0;
this.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255);
this.FlatAppearance.MouseDownBackColor = Color.FromArgb(255, 192, 192, 192);
this.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 224, 224, 224);
this.BackColor = Color.FromArgb(255, 255, 255, 255);
this.Size = new Size(100, 50);
this.CornerRadius = 10;
}
private int cornerRadius;
public int CornerRadius
{
get { return cornerRadius; }
set
{
cornerRadius = value;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
Rectangle rectangle = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
GraphicsPath path = GetRoundedRectangle(rectangle, CornerRadius);
this.Region = new Region(path);
using (Pen pen = new Pen(this.FlatAppearance.BorderColor))
{
pevent.Graphics.DrawPath(pen, path);
}
}
private GraphicsPath GetRoundedRectangle(Rectangle rectangle, int cornerRadius)
{
GraphicsPath path = new GraphicsPath();
path.StartFigure();
path.AddArc(rectangle.X, rectangle.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);
path.AddLine(rectangle.X + cornerRadius, rectangle.Y, rectangle.Right - cornerRadius * 2, rectangle.Y);
path.AddArc(rectangle.X + rectangle.Width - cornerRadius * 2, rectangle.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);
path.AddLine(rectangle.Right, rectangle.Y + cornerRadius * 2, rectangle.Right, rectangle.Bottom - cornerRadius * 2);
path.AddArc(rectangle.X + rectangle.Width - cornerRadius * 2, rectangle.Y + rectangle.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
path.AddLine(rectangle.Right - cornerRadius * 2, rectangle.Bottom, rectangle.X + cornerRadius * 2, rectangle.Bottom);
path.AddArc(rectangle.X, rectangle.Y + rectangle.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
path.CloseFigure();
return path;
}
}
```
使用 RoundButton 控件时,可以像使用普通的 Button 控件一样进行操作,例如:
```
RoundButton roundButton = new RoundButton();
roundButton.Text = "Click Me";
this.Controls.Add(roundButton);
```
这样就可以创建一个带有圆角的 button 控件了。
阅读全文