保持容器内居中一个PictureBox [英] Keeping a PictureBox centered inside a container
问题描述
我设计方法 - 用做一些基本的图像处理能力,简单的图片浏览器。目前,我有保留的问题图片框
为中心的的TabPage
所有的时间内以及保持PictureBox的宽度和大小相同的画面其展示。到目前为止,我没有成功。
I am desiging a simple picture viewer with ability to do some basic image processing. At the moment I have the problem of keeping the PictureBox
centered inside a TabPage
all the time as well as keeping the picturebox width and size same as the picture its showing. So far I had no success.
我有下面的代码,我在表格构造函数中调用它的中心位置。它工作在第一时间集中在PictureBox:
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:
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;
}
不过,这并不调整PictureBox的自己的形象(你可以看到黑色即恢复颜色PictureBox控件)部分:
But it does not resize the picturebox to its image (you can see the black part that is back color for the picturebox control):
问题是,只要我调整窗体越来越差,PictureBox的位置将进入顶部:
The problem is getting worse as soon as I resize the form, the picturebox position will goes to top:
我呼吁在窗体的resize事件上面的代码藏汉,不知道为什么它的工作原理应用程序启动时。将是很好,如果有人能告诉我什么样的属性,我应该照顾总是achive一个很好居中的PictureBox至极一样大的形象。
I call the code above in form's resize event aswell, no idea why it works when application starts. Would be nice if someone can tell me what properties I should take care of to achive a nicely centered picturebox wich always is as big as its image.
推荐答案
这是很容易,如果你只是设置锚
风格为none:
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();
}
具有锚=无
每当父容器被调整,因为它不是固定到默认Left和Top位置将中心为您服务图片框
控制。
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.
这篇关于保持容器内居中一个PictureBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!