Search code examples
c#imagepicturebox

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".


Solution

  • 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;
            }
        }
    }