C# WinForms圆角面板绘制异常的解决方案求助
C# WinForms圆角面板绘制异常的解决方案求助
大家好,我最近在做WinForms项目时,想实现一个带圆角边缘的面板,但试了几种方法都没达到预期效果,想请教下各位大佬有没有靠谱的解决办法😭
先说说我的情况:
- 我先后试了两种实现方式,但都没得到想要的结果:
第一种是自定义Panel重写OnPaint方法:
public class CustomPanel : Panel { public int CornerRadius { get; set; } = 10; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; Rectangle bounds = new Rectangle(0, 0, Width, Height); GraphicsPath path = GetRoundedRectangle(bounds, CornerRadius); using (SolidBrush brush = new SolidBrush(BackColor)) { g.FillPath(brush, path); } using (Pen pen = new Pen(BorderColor, BorderWidth)) { g.DrawPath(pen, path); } } private GraphicsPath GetRoundedRectangle(RectangleF rect, int radius) { GraphicsPath path = new GraphicsPath(); float r = radius; path.StartFigure(); path.AddArc(rect.X, rect.Y, r, r, 180, 90); path.AddArc(rect.Right - r, rect.Y, r, r, 270, 90); path.AddArc(rect.Right - r, rect.Bottom - r, r, r, 0, 90); path.AddArc(rect.X, rect.Bottom - r, r, r, 90, 90); path.CloseFigure(); return path; } public Color BorderColor { get; set; } = Color.Black; public int BorderWidth { get; set; } = 1; }
这个方法的问题是只有当面板的背景色和窗体背景色不同时才生效,如果两者背景色一致,圆角边缘就会和窗体背景混在一起,完全看不到圆角效果,这不符合我的需求。
第二种方法是调用GDI32的CreateRoundRectRgn函数,代码如下:
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] public static extern IntPtr CreateRoundRectRgn ( int top, int bot, int left, int right, int widthelipse, int heightelipse );
但这个方法我也没调试出想要的效果,还是没实现正确的圆角面板。
有没有大佬能指点下,怎么实现不管面板和窗体背景色是否一致,都能正确显示圆角的WinForms面板呀?
备注:内容来源于stack exchange,提问作者hotrodchomper
相关产品推荐
相关产品推荐

