I am trying to create a panel with rounded edges, but always comes out wrong
picture:
我试图创建一个面板与圆角边缘,但总是出来错误的图片:
what i tried was these two codes but none of them achieves my desired expectation
我尝试了这两个代码,但它们都没有达到我想要的预期
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;
}
This method works only if the panel's back color is different from the form's back color, so i need a different solution.
仅当面板的背景色与窗体的背景色不同时,此方法才有效,因此我需要不同的解决方案。
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
public static extern IntPtr CreateRoundRectRgn
(
int top,
int bot,
int left,
int right,
int widthelipse,
int heightelipse
);
更多回答
Rectangle bounds = new Rectangle(0, 0, Width - 1, Height - 1);
. Try this instead.
矩形边界=新矩形(0,0,宽度-1,高度-1);。试试这个吧。
优秀答案推荐
Seems like the right and bottom border are out of painting area. I copied your code and made it work simply by modifying this line:
右边框和底部边框似乎都不在绘画区域内。我复制了您的代码,只需修改以下行即可使其正常工作:
From:
出发地:
Rectangle bounds = new Rectangle(0, 0, Width, Height);
To:
致:
Rectangle bounds = new Rectangle(0, 0, Width - 1, Height - 1);
I reduced the panel's painting Rectangle
Width and Height by 1 pixel to ensure it inside the painting area.
我将面板的绘制矩形的宽度和高度减少了1个像素,以确保它在绘制区域内。
Hope this helps.
希望这能帮上忙。
更多回答
我是一名优秀的程序员,十分优秀!