确定源分辨率是否属于指定的宽高比

时间:2018-05-17 11:54:14

标签: c# .net vb.net aspect-ratio imaging

我想确定源解析是否属于指定的宽高比,在C#或VB.NET中。

目前我写了这个:

/// --------------------------------------------------------------------------
/// <summary>
/// Determine whether the source resolution belongs to the specified aspect ratio.
/// </summary>
/// --------------------------------------------------------------------------
/// <param name="resolution">
/// The source resolution.
/// </param>
/// 
/// <param name="aspectRatio">
/// The aspect ratio.
/// </param>
/// --------------------------------------------------------------------------
/// <returns>
/// <see langword="true"/> if the source resolution belongs to the specified aspect ratio; 
/// otherwise, <see langword="false"/>.
/// </returns>
/// ----------------------------------------------------------------------------------------------------
public static bool ResolutionIsOfAspectRatio(Size resolution, Point aspectRatio) {

    return (resolution.Width % aspectRatio.X == 0) && 
           (resolution.Height % aspectRatio.Y == 0);

}

VB.NET:

Public Shared Function ResolutionIsOfAspectRatio(resolution As Size, 
                                                 aspectRatio As Point) As Boolean

    Return ((resolution.Width Mod aspectRatio.X) AndAlso 
            (resolution.Height Mod aspectRatio.Y)) = 0

End Function

使用示例:

Size resolution = new Size(1920, 1080);
Point aspectRatio = new Point(16, 9);

bool result = ResolutionIsOfAspectRatio(resolution, aspectRatio);

Console.WriteLine(result);

我只是想确保我没有遗漏任何宽高比概念,这可能会在使用我写的函数时导致意外结果。

然后,我的问题是:对于所有情况,该算法是否正常?如果没有,我应该做哪些修改来正确执行此操作?

编辑:我注意到算法完全错误,它需要640x480作为16:9的宽高比。我没有详细了解如何计算这个基础知识。

1 个答案:

答案 0 :(得分:2)

您的计算出错。只需单独修改每个值并不验证宽高比。

e.g。

Size res = new Size(1920, 1080);
Point aspect = new Point(16, 9);  //1080%9==0 valid and true
bool result = (res.Width % aspect.X == 0) &&(res.Height % aspect.Y == 0);

是真的但是

Point aspect = new Point(16, 10); //1080%10==0 invalid and true!

也是如此。

正确的计算方法是

bool result = res.Width / aspect.X == res.Height / aspect.Y; //1920/16 == 1080/9