Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Create a Colored Border on a PictureBox Control?

Tags:

c#

I have an PictureBox and an Image in PictureBox1.Image property.
How do I place a border around the Image?

like image 562
hamed Avatar asked Dec 15 '10 03:12

hamed


1 Answers

This has always been what I use for that:

To change the border color, call this from the Paint event handler of your Picturebox control:

private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {
        ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
    }

To change the border color dynamically, for instance from a mouseclick event, I use the Tag property of the picturebox to store the color and adjust the Click event of the picturebox to retrieve it from there. For example:

if (pictureBox1.Tag == null) { pictureBox1.Tag = Color.Red; } //Sets a default color
  ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, (Color)pictureBox1.Tag, ButtonBorderStyle.Solid);

The picturebox Click event, then, would go something like this:

private void pictureBox1_Click(object sender, EventArgs e)
        {
            if ((Color)pictureBox1.Tag == Color.Red) { pictureBox1.Tag = Color.Blue; }
            else {pictureBox1.Tag = Color.Red; }
            pictureBox1.Refresh();
        }

You'll need using System.Drawing; at the beginning and don't forget to call pictureBox1.Refresh() at the end. Enjoy!

like image 151
Jim Simson Avatar answered Sep 22 '22 20:09

Jim Simson