简体   繁体   中英

C# : How to calculate aspect ratio

I am relatively new to programming. I need to calculate the aspect ratio(16:9 or 4:3) from a given dimension say axb. How can I achieve this using C#. Any help would be deeply appreciated.

public string AspectRatio(int x, int y)
{
 //code am looking for
 return ratio
}

Thanks.

You need to find Greatest Common Divisor, and divide both x and y by it.

static int GCD(int a, int b)
{
    int Remainder;

    while( b != 0 )
    {
        Remainder = a % b;
        a = b;
        b = Remainder;
    }

    return a;
}

return string.Format("{0}:{1}",x/GCD(x,y), y/GCD(x,y));

PS

If you want it to handle something like 16:10 (which can be divided by two, 8:5 will be returned using method above) you need to have a table of predefined ((float)x)/y -aspect ratio pairs

Since you only need to decide between 16:9 and 4:3, here's a much simpler solution.

public string AspectRatio(int x, int y)
{
    double value = (double)x / y;
    if (value > 1.7)
        return "16:9";
    else
        return "4:3";
}

There're only several standard ratios like: 4:3 , 5:4 , 16:10 , 16:9 . GCD is a good idea, but it will fail for at least 16:10 ratios and 1366x768 resolution.

Pure GCD algorithm will get 683:384 for 1366x768, cause 683 is a prime, while resolution is almost 16:9 (16.0078125).

I suppose, that for real tasks, one will need to implement rather complicated algorithm:

First try known aspect ratios (look for them at wikipedia ), allowing some errors and only then use GCD as fallback.

Don't forget about 32:10 ;-)

You need to find the GCD (http://en.wikipedia.org/wiki/Greatest_common_divisor) and then:

return x/GCD + ":" + y/GCD;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM