Search code examples
c#transparencypicturebox

C# Non-rectangular pictureboxes


Is there a way to create non-rectangular pictureBoxes. I have round shapes that should overlap and if possible should be in different pictureboxes.. I tried the this here, but you could not see both pictureboxes that are overlapping at a time, but just one..

Here the picture that resulted from my tests: IMG


Solution

  • You can make the PictureBoxes circular by adding an Ellipse to a GraphicsPath and then building a new Region from it.

    Here's a quick example:

    public class Target : PictureBox
    {
        public Target()
        {
            this.Size = new Size(100, 100);
            this.Paint += Target_Paint;
            Rectangle rc = this.ClientRectangle;
            rc.Inflate(-10, -10);
            System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.AddEllipse(rc);
            this.Region = new Region(gp);
        }
    
        void Target_Paint(object sender, PaintEventArgs e)
        {
            Rectangle rc = this.ClientRectangle;
            rc.Inflate(-10, -10);
            using (Pen pen = new Pen(Color.Blue, 5))
            {
                e.Graphics.DrawEllipse(pen, rc);
            }
            rc = new Rectangle(new Point(this.Size.Width / 2, this.Size.Height / 2), new Size(1, 1));
            rc.Inflate(9, 9);
            e.Graphics.FillEllipse(Brushes.Red, rc);
        }
    }
    

    After compiling, the new control appears at the top of your ToolBox.

    Here's a screenshot with three of them overlapping each other: enter image description here