3

我想将显示器的纵横比设为两位数:宽度和高度。例如 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);
    }

}

4

2 回答 2

3
  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);
}
于 2010-04-02T05:47:57.530 回答
0

我不认为有一个库函数可以做到这一点,但该代码看起来不错。与在 Javascript 中做同样事情的相关帖子中的答案非常相似: Javascript Aspect Ratio

于 2010-04-02T05:35:41.137 回答