Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 表单是否可以配置为固定的坐标范围,而不管其大小?_C#_.net_Winforms_System.drawing - Fatal编程技术网

C# 表单是否可以配置为固定的坐标范围,而不管其大小?

C# 表单是否可以配置为固定的坐标范围,而不管其大小?,c#,.net,winforms,system.drawing,C#,.net,Winforms,System.drawing,我正在使用System.drawing中的类在表单上进行一些基本绘图(用C#编写代码,与.NET4.7.2相对) 我想配置表单,以便无论表单大小如何,客户端区域的坐标范围都是(0,0)到(100100)。换句话说,如果我们最大化形式,右下角的坐标仍然应该是(100100) 不必使用我自己的缩放函数就可以完成此操作吗?您可以使用 下面是一个示例,它设置了缩放比例,使窗口坐标的宽度和高度从0到100。请注意,每当窗口大小更改时,必须重新绘制并重新计算变换: using System.Drawing;

我正在使用System.drawing中的类在表单上进行一些基本绘图(用C#编写代码,与.NET4.7.2相对)

我想配置表单,以便无论表单大小如何,客户端区域的坐标范围都是(0,0)到(100100)。换句话说,如果我们最大化形式,右下角的坐标仍然应该是(100100)

不必使用我自己的缩放函数就可以完成此操作吗?

您可以使用

下面是一个示例,它设置了缩放比例,使窗口坐标的宽度和高度从0到100。请注意,每当窗口大小更改时,必须重新绘制并重新计算变换:

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.ResizeRedraw = true;
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            setScaling(e.Graphics);
            e.Graphics.DrawRectangle(Pens.Black, 5, 5, 90, 90); // Draw rectangle close to the edges.
        }

        void setScaling(Graphics g)
        {
            const float WIDTH  = 100;
            const float HEIGHT = 100;

            g.ScaleTransform(ClientRectangle.Width/WIDTH, ClientRectangle.Height/HEIGHT);
        }
    }
}
这并没有考虑窗口的纵横比,所以即使您正在绘制一个正方形,如果窗口不是正方形,它也会显示为矩形

如果要保持方形纵横比,还可以通过计算
TranslateTransform()
来实现。请注意,这将在顶部+底部或左侧+右侧引入空白区域,具体取决于窗口的纵横比:

void setScaling(Graphics g)
{
    const double WIDTH  = 100;
    const double HEIGHT = 100;

    double targetAspectRatio = WIDTH / HEIGHT;
    double actualAspectRatio = ClientRectangle.Width / (double)ClientRectangle.Height;

    double h = ClientRectangle.Height;
    double w = ClientRectangle.Width;

    if (actualAspectRatio > targetAspectRatio)
    {
        w = h * targetAspectRatio;
        double x = (ClientRectangle.Width - w) / 2;
        g.TranslateTransform((float)x, 0);
    }
    else
    {
        h = w / targetAspectRatio;
        double y = (ClientRectangle.Height - h) / 2;
        g.TranslateTransform(0, (float)y);
    }

    g.ScaleTransform((float)(w / WIDTH), (float)(h / HEIGHT));
}

就我而言,保持纵横比并不重要,但手边有代码很好,谢谢。这两个例子都非常有效。通过在第一个示例中使用ScaleTransform,我现在“明白了”。谢谢:-)