views:

188

answers:

2

I want to get aspect ratio of a monitor as two digits : width and height. For example 4 and 3, 5 and 4, 16 and 9.

I wrote some code for that task. Maybe it is any easier way to do that ? For example, some library function =\

/// <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);
    }

}

A: 

I don't think there's a library function to do it, but that code looks good. Very similar to the answer in this related post of doing the same thing in Javascript: Javascript Aspect Ratio

cpalmer
-1: I would disagree with the `thought` that this is not possible.
KMan
+1  A: 
  1. Use Screen class to get the height/width.
  2. Divide to get the GCD
  3. Calculate the ratio.

See following code:

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);
}
KMan
As I thought, There is no library function. Thanks for an answer anyway ;)
Alexander Stalt