title: Keeping a PictureBox centered inside a container
body: <p>I am designing a simple picture viewer with ability to do some basic image processing. At the moment I have the problem of keeping the <code>PictureBox</code> centered inside a <code>TabPage</code> all the time as well as keeping the picturebox width and size same as the picture its showing. So far I had no success.</p>
  <p>I have the following code that I call in form constructor to position it in center. it works the first time to center the picturebox:</p>
  <pre><code>private void SetPictureBoxOriginalSizeAndLocation(bool makeImageNull = false, DockStyle dockStyle = DockStyle.None)
  {
      if (makeImageNull) picBoxView.Image = null;
      picBoxView.Dock = dockStyle;
  
      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;
  
      if (picBoxView.Image == null) return;
  
      //Resize image according to width
      picBoxView.Image = ImageMethods.ResizeImage(picBoxView.Image.Tag.ToString(), width, height, false); 
  
      picBoxView.Location = new Point(xPoint, yPoint);
      picBoxView.Width = width;
      picBoxView.Height = height;
  }
  </code></pre>
  <p>But it does not resize the picturebox to its image (you can see the black part that is back color for the picturebox control):</p>
  <p><img src="https://i.stack.imgur.com/OFMYa.png" alt="IT is ok the first time" /></p>
  <p>The problem is getting worse as soon as I resize the form, the picturebox position will goes to top:</p>
  <p><img src="https://i.stack.imgur.com/q2R0u.png" alt="Form resized" /></p>
  <p>I call the code above in form's resize event as well, no idea why it works when application starts. Would be nice if someone can tell me what properties I should take care of to achieve a nicely centered picturebox which always is as big as its image.</p>