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

所以我想做一个 if 语句,如果图像对于图像框的初始大小 (520, 301) 来说太大了,将图像框的大小模式设置为自动调整大小,否则就把它放在那里。

我很确定你可以用这个来改变它:

picturebox1.SizeMode = PictureBoxSizeMode.AutoSize;

但是我不知道if语句怎么写

只需将您的文件加载到 Bitmap,然后将其 HeightWidth 属性 与我们的自定义尺寸 (500 x 301) 进行比较。喜欢

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

您可以在将图像分配给您的图片框之前将其临时存储,然后将其大小与您的框的大小进行比较。

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;

   }
}