Rounded edges in picturebox C#

2020-01-29 05:56发布

问题:

How to round edges in picturebox control. I Want to get angles like ellipse have but i dont know how to do it. I Use C#. Thanks!

回答1:

Yes, no problem, you can give a control an arbitrary shape with its Region property. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class OvalPictureBox : PictureBox {
    public OvalPictureBox() {
        this.BackColor = Color.DarkGray;
    }
    protected override void OnResize(EventArgs e) {
        base.OnResize(e);
        using (var gp = new GraphicsPath()) {
            gp.AddEllipse(new Rectangle(0, 0, this.Width-1, this.Height-1));
            this.Region = new Region(gp);
        }
    }
}


回答2:

putting 1 Picture box on the form and write this code also you can change the the minus number beside of Width and Height to get best result

 System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.AddEllipse(0, 0, pictureBox1.Width - 3, pictureBox1.Height - 3);
            Region rg = new Region(gp);
            pictureBox1.Region = rg;



回答3:

Round edges as in round corners?

If so check out http://social.msdn.microsoft.com/forums/en-US/winforms/thread/603084bb-1aae-45d1-84ae-8544386d58fd

Rectangle r = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
int d = 50;
gp.AddArc(r.X, r.Y, d, d, 180, 90);
gp.AddArc(r.X + r.Width - d, r.Y, d, d, 270, 90);
gp.AddArc(r.X + r.Width - d, r.Y + r.Height - d, d, d, 0, 90);
gp.AddArc(r.X, r.Y + r.Height - d, d, d, 90, 90);
pictureBox1.Region = new Region(gp);


回答4:

Thank you, Hans. But I also need a smooth look. I did some research on this subject, but I could not find a solution. Then I tried to do it myself and found the solution below. Maybe someone else needs it.

protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (GraphicsPath gp = new GraphicsPath())
        {
            gp.AddEllipse(0, 0, this.Width - 1, this.Height - 1);
            Region = new Region(gp);
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.DrawEllipse(new Pen(new SolidBrush(this.BackColor), 1), 0, 0, this.Width - 1, this.Height - 1);
        }
    }