Keeping a PictureBox centered inside a container

Givien a Form with TabControl, which has Dock set to Fill, below will keep your PictureBox in the centre. It also sets PictureBox size to Bitmap size:

    public partial class Form1 : Form
    {
        Bitmap b = new Bitmap(320, 200);
        public Form1()
        {
            InitializeComponent();
            CenterTheBox();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            CenterTheBox();
        }

        void CenterTheBox()
        {
            pictureBox1.Size = b.Size;
            var left = (tabPage1.ClientRectangle.Width - pictureBox1.ClientRectangle.Width) / 2;
            var top = (tabPage1.ClientRectangle.Height - pictureBox1.ClientRectangle.Height) / 2;
            pictureBox1.Location = new Point(tabPage1.ClientRectangle.Location.X + left, tabPage1.ClientRectangle.Location.Y + top);

        }
    }

It's pretty easy if you just set the Anchor style to none:

picBoxView = new PictureBox();
picBoxView.SizeMode = PictureBoxSizeMode.AutoSize;
picBoxView.Anchor = AnchorStyles.None;
tabImageView.Controls.Add(picBoxView);
CenterPictureBox(picBoxView, myImage);

Then just center the PictureBox initially whenever you change the image of the PictureBox:

private void CenterPictureBox(PictureBox picBox, Bitmap picImage) {
  picBox.Image = picImage;
  picBox.Location = new Point((picBox.Parent.ClientSize.Width / 2) - (picImage.Width / 2),
                              (picBox.Parent.ClientSize.Height / 2) - (picImage.Height / 2));
  picBox.Refresh();
}

Having the Anchor = None will center the PictureBox control for you whenever the parent container gets resized because it "isn't" anchored to the default Left and Top locations.


I believe your problem lies here

var xPoint = tabImageView.Location.X + ((splitContainer.Panel2.Width / 2) / 2);
var yPoint = tabImageView.Location.Y;

var width = tabImageView.Width / 2;
var height = (tabImageView.Height / 2) - toolStripImageView.Height;

ypoint is alwways set to tabImageView Y, althought it should be set to

tabImageView.Location.Y + (tabImageView.Size.Height - picBoxView.Size.Height)/2

should be almost the same with xPoint

tabImageView.Location.X + (tabImageView.Size.Width - picBoxView.Size.Width)/2

and

width = picBoxView.Image.Width;
height = picBoxView.Image.Height;