c# - 获取显示器的纵横比

标签 c# winforms aspect-ratio

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

最佳答案

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

关于c# - 获取显示器的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2565128/

相关文章:

c# - 如何对按钮 WPF 进行分组?

c# - 验证并打印小数点后两位的 double 值

c# - Waitform 上的进度条使用在另一个线程上运行的任务卡住

android - 如何在不创建新位图的情况下拥有圆形、中心裁剪的 imageView?

css - 自动调整 Web 应用程序的高度和宽度

c# - 并行处理一个密集的IO函数

c# - 如何从列表中选择在另一个列表/模型中没有相关对象的所有对象

c# - 从asp.net代码中获取某个网站的源码

c# winforms 如何旋转图像(但不围绕其中心旋转)

ffmpeg - 通过设置高度比修改后如何让ffmpeg计算宽度?