简体   繁体   English

C#-更改图片框的SizeMode

[英]C# - Changing SizeMode of picturebox

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog open = new OpenFileDialog();
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.png; *.bmp";
        if(open.ShowDialog() == DialogResult.OK)
        {
            tbFileName.Text = open.FileName;
            pictureBox1.Image = new Bitmap(open.FileName);
        }
    }

So I want to make an if statement, if the image is too big for the initial size of the image box (520, 301), set the image box sizemode to autosize, otherwise just put it in there. 所以我想做一个if语句,如果图像对于图像框的初始大小来说太大(520,301),则将图像框的sizemode设置为autosize,否则就将其放入其中。

I'm pretty sure that you can change it by using this: 我很确定您可以使用以下方法进行更改:

picturebox1.SizeMode = PictureBoxSizeMode.AutoSize;

But I don't know how to write the if statement. 但是我不知道如何编写if语句。

Just load your file to Bitmap and then compare its Height and Width property with our custom size (500 x 301). 只需将文件加载Bitmap ,然后将其“ Height和“ Width属性与我们的自定义大小(500 x 301)进行比较即可。 like 喜欢

...
tbFileName.Text = open.FileName;

using (Bitmap bmp = new Bitmap(open.FileName))
{
    if (bmp.Height >= 301 && bmp.Width >= 500)
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

    pictureBox1.Image = bmp;
}

You could store your image temporary before assigning it to your picturebox and compare the size of it with the size of your box. 您可以先将图像临时存储,然后再将其分配到图片框,然后将其大小与框的大小进行比较。

private void button1_Click(object sender, EventArgs e)
{
   OpenFileDialog open = new OpenFileDialog();
   open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.png; *.bmp";
   if (open.ShowDialog() == DialogResult.OK)
   {
      Bitmap tmp = new Bitmap(open.FileName);

      if(tmp.Height >= pictureBox1.Height || tmp.Width >= pictureBox1.Width)
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

      pictureBox1.Image = tmp;

   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM