Search code examples
c#asp.netaspect-ratio

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.


Solution

  • 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