【问题标题】:Get aspect ratio of a monitor获取显示器的纵横比
【发布时间】:2011-02-03 15:22:41
【问题描述】:

我想将显示器的纵横比设为两位数:宽度和高度。例如 4 和 3、5 和 4、16 和 9。

我为该任务编写了一些代码。也许这是更简单的方法?比如一些库函数=\

/// <summary>
/// Aspect ratio.
/// </summary>
public struct AspectRatio
{
    int _height;
    /// <summary>
    /// Height.
    /// </summary>
    public int Height
    {
        get
        {
            return _height;
        }
    }

    int _width;
    /// <summary>
    /// Width.
    /// </summary>
    public int Width
    {
        get
        {
            return _width;
        }
    }

    /// <summary>
    /// Ctor.
    /// </summary>
    /// <param name="height">Height of aspect ratio.</param>
    /// <param name="width">Width of aspect ratio.</param>
    public AspectRatio(int height, int width)
    {
        _height = height;
        _width = width;
    }
}



public sealed class Aux
{
    /// <summary>
    /// Get aspect ratio.
    /// </summary>
    /// <returns>Aspect ratio.</returns>
    public static AspectRatio GetAspectRatio()
    {
        int deskHeight = Screen.PrimaryScreen.Bounds.Height;
        int deskWidth = Screen.PrimaryScreen.Bounds.Width;

        int gcd = GCD(deskWidth, deskHeight);

        return new AspectRatio(deskHeight / gcd, deskWidth / gcd);
    }

    /// <summary>
    /// Greatest Common Denominator (GCD). Euclidean algorithm. 
    /// </summary>
    /// <param name="a">Width.</param>
    /// <param name="b">Height.</param>
    /// <returns>GCD.</returns>
    static int GCD(int a, int b)
    {
        return b == 0 ? a : GCD(b, a % b);
    }

}

【问题讨论】:

    标签: c# winforms aspect-ratio


    【解决方案1】:

    我认为没有库函数可以执行此操作,但该代码看起来不错。与在 Javascript 中做同样事情的相关帖子中的答案非常相似:Javascript Aspect Ratio

    【讨论】:

    • -1:我不同意thought 认为这是不可能的。
    【解决方案2】:
    1. 使用Screen 类获取高度/宽度。
    2. 除以得到GCD
    3. 计算比率。

    见以下代码:

    private void button1_Click(object sender, EventArgs e)
    {
        int nGCD = GetGreatestCommonDivisor(Screen.PrimaryScreen.Bounds.Height, Screen.PrimaryScreen.Bounds.Width);
        string str = string.Format("{0}:{1}", Screen.PrimaryScreen.Bounds.Height / nGCD, Screen.PrimaryScreen.Bounds.Width / nGCD);
        MessageBox.Show(str);
    }
    
    static int GetGreatestCommonDivisor(int a, int b)
    {
        return b == 0 ? a : GetGreatestCommonDivisor(b, a % b);
    }
    

    【讨论】:

    • 我想,没有库函数。无论如何感谢您的回答;)
    • 我的屏幕分辨率是 1813x1024,不知道为什么返回“1024:1813”?
    • 我的屏幕分辨率是 1366* 768 但它返回 384:683 !我能做什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多