C# - 在面板上绘制圆角矩形

时间:2016-07-21 09:00:51

标签: c#

我目前正在尝试将渐变填充圆角矩形绘制到表单中的bar面板上。

从一些研究中我发现了一些允许我创建自定义矩形的代码:

static class CustomRectangle 
{
    public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
    {
        int diameter = radius * 2;
        Size size = new Size(diameter, diameter);
        Rectangle arc = new Rectangle(bounds.Location, size);
        GraphicsPath path = new GraphicsPath();

        if (radius == 0)
        {
            path.AddRectangle(bounds);
            return path;
        }

        // top left arc  
        path.AddArc(arc, 180, 90);

        // top right arc  
        arc.X = bounds.Right - diameter;
        path.AddArc(arc, 270, 90);

        // bottom right arc  
        arc.Y = bounds.Bottom - diameter;
        path.AddArc(arc, 0, 90);

        // bottom left arc 
        arc.X = bounds.Left;
        path.AddArc(arc, 90, 90);

        path.CloseFigure();
        return path;
    }

    public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius)
    {
        if (graphics == null)
            throw new ArgumentNullException("graphics");
        if (brush == null)
            throw new ArgumentNullException("brush");

        using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
        {
            graphics.FillPath(brush, path);
        }
    }

归功于此page

接下来使用此自定义矩形,我尝试使用paint面板的bar方法。

private void quickMenuBar_Paint(object sender, PaintEventArgs e)
    {
        LinearGradientBrush myBrush = new LinearGradientBrush(new Point(20, 20), new Point(120, 520), Color.DarkBlue, Color.RoyalBlue);
        System.Drawing.Graphics formGraphics = this.CreateGraphics();

        CustomRectangle.FillRoundedRectangle(formGraphics, myBrush, new System.Drawing.Rectangle(20, 20, 100, 500), 25);
        myBrush.Dispose();
        formGraphics.Dispose();
}

但是在执行此代码后,它只会在表单上和bar面板后面直接打印一个圆角矩形。

我还有其他方法使用PaintEventArgs e

为标准矩形填充面板
e.Graphics.FillRectangle(myBrush , otherBar.ClientRectangle);

所以显然我需要在我的自定义矩形方法中使用PaintEventArgs e,但我不知道如何或在哪里。

如果有更好的方法来绘制圆形的直角,请分享。

1 个答案:

答案 0 :(得分:2)

您通常不应该使用CreateGraphics()。只需删除此行:

System.Drawing.Graphics formGraphics = this.CreateGraphics();

并使用e.Graphics之前使用formGraphics的位置。 Paint事件基本上是要求您为我绘制一些东西,这里是要绘制的图形对象"。

由于您已经为圆角矩形方法提供了Graphics对象实例,因此不需要进行任何更改。