winforms 在C# windows窗体中绘制圆边面板无法正确加载

lf5gs5x2  于 2023-10-23  发布在  C#
关注(0)|答案(1)|浏览(102)

我试图创建一个面板与圆角边缘,但总是出来错误的图片:

我尝试的是这两个代码,但它们都没有达到我的预期

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;
}

只有当面板的背景颜色与窗体的背景颜色不同时,此方法才有效,因此我需要不同的解决方案。

[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
public static extern IntPtr CreateRoundRectRgn
    (
    int top,
    int bot,
    int left,
    int right,
    int widthelipse,
    int heightelipse
    );
7jmck4yq

7jmck4yq1#

看起来右边和底部边框超出了绘画区域。我复制了你的代码,并通过修改这一行使它工作:
发件人:

Rectangle bounds = new Rectangle(0, 0, Width, Height);

收件人:

Rectangle bounds = new Rectangle(0, 0, Width - 1, Height - 1);

我将面板的绘画Rectangle宽度和高度减少了1个像素,以确保它在绘画区域内。

希望这对你有帮助。

相关问题