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".
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;
}
}
}
This can easily be done with the SizeMode property
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
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;
}
}
}
What's wrong with using Padding?
void picturebox_Paint(object sender, PaintEventArgs e)
{
int a = picturebox.Width - picturebox.Image.Width;
int b = picturebox.Height - picturebox.Image.Height;
Padding p = new System.Windows.Forms.Padding();
p.Left = a / 2;
p.Top = b / 2;
picturebox.Padding = p;
}
© 2022 - 2024 — McMap. All rights reserved.