如果你想要真正的圆角而不仅仅是透明的技巧,你可以使用这个例子:
private int radius = 20;
[DefaultValue(20)]
public int Radius
{
get { return radius; }
set
{
radius = value;
this.RecreateRegion();
}
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect,
int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);
private GraphicsPath GetRoundRectagle(Rectangle bounds, int radius)
{
float r = radius;
GraphicsPath path = new GraphicsPath();
path.StartFigure();
path.AddArc(bounds.Left, bounds.Top, r, r, 180, 90);
path.AddArc(bounds.Right - r, bounds.Top, r, r, 270, 90);
path.AddArc(bounds.Right - r, bounds.Bottom - r, r, r, 0, 90);
path.AddArc(bounds.Left, bounds.Bottom - r, r, r, 90, 90);
path.CloseFigure();
return path;
}
private void RecreateRegion()
{
var bounds = ClientRectangle;
//using (var path = GetRoundRectagle(bounds, this.Radius))
// this.Region = new Region(path);
//Better round rectangle
this.Region = Region.FromHrgn(CreateRoundRectRgn(bounds.Left, bounds.Top,
bounds.Right, bounds.Bottom, Radius, radius));
this.Invalidate();
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
this.RecreateRegion();
}
具有 GraphicsPath 的区域:
具有 Windows API 的区域:
这种方法与透明化的区别:
- 设置圆形区域,控件具有真正的圆角,您可以看到圆形部分后面的内容,尽管当它是透明的时,您会看到表单的背景。
- 设置圆形区域,当您单击删除的圆形部分时,单击穿过该区域并到达后面,但如果您使用透明技巧,则单击透明区域将由控件处理。
您可以使用这两个选项中的任何一个。根据您的要求制作透明或设置区域。
Download
您可以在此处下载代码或克隆存储库:
- r-aghaei/RoundCornerControl示例 https://github.com/r-aghaei/RoundCornerControlExample