Rounded edges in button C# (WinForms)

后端 未结 6 478
时光说笑
时光说笑 2020-11-29 07:07

\"It's

Hello, through some research around here and other sites, I\'ve made a roun

6条回答
  •  一个人的身影
    2020-11-29 07:23

    This is a tweak on TaW's answer to more easily tweak the borderRadius and borderThickness. If you get random white space between the border and the button background color, m needs to be tweaked.

    public class RoundedButton : Button
    {
      GraphicsPath GetRoundPath(RectangleF Rect, int radius)
      {
        float m = 2.75F;
        float r2 = radius / 2f;
        GraphicsPath GraphPath = new GraphicsPath();
    
        GraphPath.AddArc(Rect.X + m, Rect.Y + m, radius, radius, 180, 90);
        GraphPath.AddLine(Rect.X + r2 + m, Rect.Y + m, Rect.Width - r2 - m, Rect.Y + m);
        GraphPath.AddArc(Rect.X + Rect.Width - radius - m, Rect.Y + m, radius, radius, 270, 90);
        GraphPath.AddLine(Rect.Width - m, Rect.Y + r2, Rect.Width - m, Rect.Height - r2 - m);
        GraphPath.AddArc(Rect.X + Rect.Width - radius - m,
                       Rect.Y + Rect.Height - radius - m, radius, radius, 0, 90);
        GraphPath.AddLine(Rect.Width - r2 - m, Rect.Height - m, Rect.X + r2 - m, Rect.Height - m);
        GraphPath.AddArc(Rect.X + m, Rect.Y + Rect.Height - radius - m, radius, radius, 90, 90);
        GraphPath.AddLine(Rect.X + m, Rect.Height - r2 - m, Rect.X + m, Rect.Y + r2 + m);
    
        GraphPath.CloseFigure();
        return GraphPath;
      }
    
      protected override void OnPaint(PaintEventArgs e)
      {
        int borderRadius = 50;
        float borderThickness = 1.75f;
        base.OnPaint(e);
        RectangleF Rect = new RectangleF(0, 0, this.Width, this.Height);
        GraphicsPath GraphPath = GetRoundPath(Rect, borderRadius);
    
        this.Region = new Region(GraphPath);
        using (Pen pen = new Pen(Color.Silver, borderThickness))
        {
          pen.Alignment = PenAlignment.Inset;
          e.Graphics.DrawPath(pen, GraphPath);
        }
      }
    }
    

    Cheers!

提交回复
热议问题