当我调整主窗体的大小时,如何将图片框保持为正方形? [英] How to keep picture-box as square when I resize the main form?

查看:92
本文介绍了当我调整主窗体的大小时,如何将图片框保持为正方形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨亲爱的

我想在调整表格大小的同时保留我的图片框大小,但是一旦我重新调整表格大小,图片框的宽长比就会发生变化,我不知道不希望它。

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.

推荐答案

这里有一种方法可以解决这个问题:为PictureBox SizeChanged事件创建一个EventHandler:
Here's one way you could approach this: create an EventHandler for the PictureBox SizeChanged Event:
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.


我认为你已经激活了底部和右侧锚点图片框。

我认为你应该尝试只激活图片框顶部和左边的锚点。



欢呼,

Marco
What I think is happening that you have activated the bottom and right anchor of the picture box.
I think that you should try to only activate the Anchors to top and left of the picture box.

cheers,
Marco


这篇关于当我调整主窗体的大小时,如何将图片框保持为正方形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆