How to Draw a Border Around an Image in a PictureBox

Once again it turned out that less is sometimes more and that for what I needed, just a few commands are enough. Specifically, you need to follow these rules:

  1. Always draw in the Paint event of the PictureBox control, because that is the only place where you have a graphics context that actually works
  2. Do not store the created image back in the PB; it is enough to create a graphics context (an object of type Graphics) from the image in the PB and the references inside the object take care of the rest. On top of that, I use 2 PBs here, and for some reason, when I did this, another image refused to load into PB1 (PB2 was the one I was drawing the border on).
  3. Shrink the image in the PB to the size of the PB – otherwise the border is drawn around the whole image, for example when you use SizeMode Zoom in the PB and the image adapts to the size of the PB, and you will see only the left and top edges. Likewise, if the image were smaller than the PB, the border would not go around the whole PB.

And now for the code itself. It all comes down to these few lines:

C#
void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    DrawBorder(g);
}
private void DrawBorder(Graphics g)
{
    if (pictureBox2.Image != null)
    {
        Pen p = new Pen(Color.Blue);
        p.Width = 5;
        //-These values are the defaults, no need to set them
        Image image = null;
        image = pictureBox2.Image;
        g.DrawImage(image, new Point(0, 0));
        g.DrawRectangle(p, new Rectangle(0, 0, pictureBox2.Image.Width, pictureBox2.Image.Height));
        Bitmap outputBitmap = new Bitmap(pictureBox2.Image.Width, pictureBox2.Image.Height, g);
        //-Dispose of objects we no longer need to free up resources
        p.Dispose();
        //-This one is not disposed, because the program would then throw an "ArgumentException"
        //-Never do this, because then something else stops working - in my case PB1
    }
}

And the result looks like this:

Border drawn around the image

Categories

Leave a Reply