【问题标题】:Image FILL logic such as "Stretch.Uniform" of WPFWPF的“Stretch.Uniform”等图像填充逻辑
【发布时间】:2019-09-28 07:18:54
【问题描述】:

我正在寻找要在我的控制台应用程序中应用的图像填充逻辑,它会生成 TIFF 文件。我的图像容器尺寸为 1200 * 1800 像素。

已应用以下逻辑来调整图像大小以适应此尺寸,但此逻辑应用 FIT 部分而不是 FILL 部分。

如果我的图像尺寸为 1200 * 1600,那么我会在下面得到空白区域,如果我尝试将图像放入容器中,那么它会拉伸图像并且图像看起来不太好. 1200 * 1600 上面的图片非常适合。

我正在寻找类似于 WPF 应用程序的“Stretch.Uniform”的逻辑,它可以均匀地填充图像而不会丢失图像的实际视图。

private static Dimension getScaledDimension(Dimension imgSize, Dimension boundary)
{

    int original_width = imgSize.width;
    int original_height = imgSize.height;
    int bound_width = boundary.width;
    int bound_height = boundary.height;
    int new_width = original_width;
    int new_height = original_height;

    // first check if we need to scale width. 
    if (original_width > bound_width)  
    {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }


    // then check if we need to scale even with the new height. 
    if (new_height > bound_height)
    {
        //scale height to fit instead
        new_height = bound_height;
        //scale width to maintain aspect ratio
        new_width = (new_height * original_width) / original_height;
    }

    return new Dimension { height = new_height, width = new_width };
}

【问题讨论】:

    标签: c# wpf image-scaling


    【解决方案1】:

    检查 2 个矩形的纵横比以决定适合哪个属性。

    private static Dimension getScaledDimension(Dimension imgSize, Dimension boundary)
    {
        int original_width = imgSize.width;
        int original_height = imgSize.height;
        int bound_width = boundary.width;
        int bound_height = boundary.height;
    
        double original_aspect = (double)original_width / original_height;
        double bound_aspect = (double)bound_width / bound_height;
    
        //original size is wider than boundary, fit boundary width
        if(original_aspect > bound_aspect)
        {
            return new Dimension
            {
                width = boundary.width,
                height = (int)Math.Round(boundary.width / original_aspect)
            };
        }
    
        //original size is taller than boundary, fit boundary height
        else
        {
            return new Dimension
            {
                height = boundary.height,
                width = (int)Math.Round(boundary.height * original_aspect)
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 2022-08-19
      • 2013-09-12
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      相关资源
      最近更新 更多