问题描述
嗨亲爱的
我想在调整表格大小的同时保留我的图片框大小,但是一旦我重新调整表格大小,图片框的宽长比就会发生变化,我不知道不希望它。
Hi dears
I want to keep my picture box size while I resize my form, but as soon as I re-size the form the picture box' width-length ratio changes, which I don't want it to.
推荐答案
private void pictureBox1_SizeChanged(object sender, EventArgs e)
{
if (pictureBox1.Width == pictureBox1.Height) return;
if (pictureBox1.Width > pictureBox1.Height)
{
pictureBox1.Height = pictureBox1.Width;
}
else
{
pictureBox1.Width = pictureBox1.Height;
}
}
此处显示的代码将调整 PictureBox的宽度或高度等于更大的尺寸。
如果你的PictureBox以只宽度可以改变的方式锚定,那么你可以通过仅测试Width>来简化上面的代码。高度,并调整高度。
您还可以通过设置其MinimumSize和MaximumSize属性来约束PictureBox大小。或者,您可以在SizeChanged EventHandler中约束大小。
您还应该考虑PictureBox位置调整后的可能效果:取决于位置和完成缩放后,PictureBox可能会部分地位于Form或其他ContainerControl的边界之外。
请注意,当您启动WinForms程序时,SizeChanged EventHandler将会程序启动时调用两次(如果你不喜欢这个,请告诉微软)。我经常在Form Load EventHandler中设置一个布尔标志,然后在像PictureBox这样的控件中测试该布尔标志,如果是真的则退出EventHandler。我通常在Form Load EventHandler的末尾将该boolean标志重置为false,在Form Shown EventHandler中更少。
The code shown here will adjust either the Width or Height of the PictureBox to be equal to the larger dimension.
If your PictureBox is anchored in a way that only the Width can change, then you can simplify the above code by only testing for Width > Height, and adjusting the Height.
You could also constrain the PictureBox size by setting its MinimumSize and MaximumSize properties. Or, you could, in the SizeChanged EventHandler, constrain the size.
You also should consider the possible effect of the PictureBox's Location when it's resized: depending on the Location and the scaling done, the PictureBox could become partially outside your Form, or other ContainerControl's, bounds.
Note that when you launch a WinForms program, the SizeChanged EventHandler is going to be called twice by the program starting up (tell Microsoft if you don't like this). Often I set a boolean flag in a Form Load EventHandler, and then, in Controls like the PictureBox I test for that boolean flag and exit the EventHandler if it's true. I usually reset that boolean flag to false at the end of the Form Load EventHandler, less often in the Form Shown EventHandler.
这篇关于当我调整主窗体的大小时,如何将图片框保持为正方形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!