保持PictureBox在容器内居中

我正在设计一个简单的图片浏览器,能够进行一些基本的图像处理。 目前我遇到的问题是始终将PictureBox保持在TabPage内部,并保持PictureBox的宽度和大小与其显示的图片相同。 到目前为止,我没有成功。

我有以下代码,我在表单构造函数中调用它来将其定位在中心。 它第一次使图片框居中:

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

但它不会将图片框调整为其图像(您可以看到图片框控件的背面颜色为黑色部分):

第一次,这是好的

一旦我调整表单大小,问题就越来越严重,图片框位置将会变为顶部:

表格已调整大小

我在表单的resize事件中调用上面的代码,也不知道为什么它在应用程序启动时有效。 如果有人可以告诉我应该照顾哪些属性以获得一个总是与其图像一样大的精美居中的图片框,那将是很好的。

如果您只将Anchor样式设置为none,那将非常简单:

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

每当您更改PictureBox的图像时,最初只是将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(); } 

每当父容器resize时,具有Anchor = None将使PictureBox控件居中,因为它“未”锚定到默认的Left和Top位置。

Givien带有TabControlForm ,其Dock设置为Fill ,下面将使PictureBox保持在中心位置。 它还将PictureBox大小设置为Bitmap大小:

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

我相信你的问题就在这里

 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被设置为tabImageView Y,但是应该设置为

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

应该与xPoint几乎相同

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

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