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
);
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.
Hope this helps.