【问题标题】:How to get displayed Image dimensions of an Image scaled to fit a PictureBox如何显示缩放以适合 PictureBox 的图像的图像尺寸
【发布时间】:2014-05-14 15:58:59
【问题描述】:

我想知道是否可以获得已调整大小以适合 PictureBox 的图像的显示图像尺寸。

PictureBox 的 SizeMode 属性设置为 Zoom。因此保留了原始图像的纵横比。但是,我需要获取显示的图像大小,这不是通过 API 公开的。

我已经阅读了一些包含反射的答案,但我不想这样做。

【问题讨论】:

  • @GrantWinney 是的窗口表单

标签: c# winforms picturebox


【解决方案1】:

最简单的方法是自己获取纵横比,毕竟这是简单的数学运算。

首先确定图像是垂直的还是水平的,然后简单地获取图片框的高度或宽度(分别)并根据该值确定原始图像的宽高比的宽度或高度(分别)。

OriginalImg.Height / OriginalImage.Width x PictureBox.Width = PictureBox.Height

【讨论】:

  • 不是很准确。始终使用 ClientSize 代替。请记住,图像需要缩放以适应宽度高度。
【解决方案2】:

这个函数做你想做的事:

private Size GetDisplayedImageSize(PictureBox pictureBox)
{
    Size containerSize = pictureBox.ClientSize;
    float containerAspectRatio = (float)containerSize.Height / (float)containerSize.Width;
    Size originalImageSize = pictureBox.Image.Size;
    float imageAspectRatio = (float)originalImageSize.Height / (float)originalImageSize.Width;

    Size result = new Size();
    if (containerAspectRatio > imageAspectRatio)
    {
        result.Width = containerSize.Width;
        result.Height = (int)(imageAspectRatio * (float)containerSize.Width);
    }
    else
    {
        result.Height = containerSize.Height;
        result.Width = (int)((1.0f / imageAspectRatio) * (float)containerSize.Height);
    }
    return result;
}

【讨论】:

    【解决方案3】:

    你必须使用PictureBox吗?我找到了thread,他们提供了一些选项来解决您的问题。不过好像有点脏……

    1) 将 PictureBox 设置为 Normal 或 Center Image,然后自己调整 Image 的大小(使用 Form Resize 事件),这里处理所有的数学运算有点复杂,但非常可行...(参见裁剪/缩放线程注意:这是 VB6 代码,但数学相同)

    2) 只需使用数学并计算位置...同样,数学有点复杂但也是可行的..(有关数学,请参见与上述相同的线程)..

    我想它是一个 WinForms 应用程序。或者你也可以使用 WPF 控件吗?

    在 WPF 中,您可以通过 ActualWidth 和 ActualHeight 获取尺寸。

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      相关资源
      最近更新 更多