Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center image in picturebox on resize?

How can I center an image in a picturebox as I resize the form? What I have is a picturebox in a panel so if the image is larger than the picturebox, I can get scrollbars on the panel. But this doesn't work with the picturebox size mode "Center Image" and only works with "Auto Size".

like image 794
Jack Avatar asked Jul 30 '11 11:07

Jack


2 Answers

This can easily be done with the SizeMode property

pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
like image 184
user2954518 Avatar answered Oct 03 '22 01:10

user2954518


Don't use a PictureBox here, a Panel is already perfectly capable of displaying a centered image through its BackgroundImage property. All that's needed is to turn on its DoubleBuffered property to suppress flicker. 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, replacing the panel. Assign its BackgroundImage property with the Properties window or in your code.

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

internal class PicturePanel : Panel {
    public PicturePanel() {
        this.DoubleBuffered = true;
        this.AutoScroll = true;
        this.BackgroundImageLayout = ImageLayout.Center;
    }
    public override Image BackgroundImage {
        get { return base.BackgroundImage; }
        set { 
            base.BackgroundImage = value;
            if (value != null) this.AutoScrollMinSize = value.Size;
        }
    }
}
like image 37
Hans Passant Avatar answered Oct 03 '22 00:10

Hans Passant