2010-04-02 2 views
3

Je souhaite obtenir le rapport d'aspect d'un moniteur en deux chiffres: largeur et hauteur. Par exemple 4 et 3, 5 et 4, 16 et 9.Obtenir le rapport d'aspect d'un moniteur

J'ai écrit du code pour cette tâche. Peut-être que c'est un moyen plus facile de le faire? Par exemple, une fonction de bibliothèque = \

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

}

Répondre

1
  1. Utilisez Screen classe pour obtenir la hauteur/largeur. Diviser pour obtenir le GCD
  2. Calculez le ratio.

Voir le code suivant:

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); 
} 
+0

Comme je le pensais, il n'y a pas de fonction de bibliothèque. Merci pour une réponse de toute façon;) –

+0

Ma résolution d'écran est 1813x1024 et je ne sais pas pourquoi il a retourné "1024: 1813"? –

+0

Ma résolution d'écran est 1366 * 768 mais elle renvoie 384: 683! Que puis-je faire – user3290286

0

Je ne pense pas qu'il y ait une fonction de bibliothèque pour le faire, mais ce code semble bon. Très similaire à la réponse dans cet article connexe de faire la même chose en Javascript: Javascript Aspect Ratio

+0

-1: Je suis en désaccord avec le 'thought' que cela est impossible. –