在不影响内容的情况下调整大小 window

resizing window without affecting content

我正在尝试添加调整应用程序大小的功能 window 而不会导致 window 的内容同时拉伸。我尝试更改 if 语句并尝试不同的比率计算以不影响

protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);

        if (mShader != null)
        {
            int uProjectionLocation = GL.GetUniformLocation(mShader.ShaderProgramID, "uProjection");
            int windowHeight = ClientRectangle.Height;
            int windowWidth = ClientRectangle.Width;
            if (windowHeight > windowWidth)
            {
                if (windowWidth < 1)
                {
                    windowWidth = 1;
                }
                float ratio = windowWidth / windowHeight;
                Matrix4 projection = Matrix4.CreateOrthographic(ratio * 10, ratio * 10, -1, 1);
                GL.UniformMatrix4(uProjectionLocation, true, ref projection);
            }
            else if(windowHeight < windowWidth)
            {
                if (windowHeight < 1)
                {
                    windowHeight = 1;
                }
                float ratio = windowWidth / windowHeight;
                Matrix4 projection = Matrix4.CreateOrthographic(ratio * 10, ratio * 10, -1, 1);
                GL.UniformMatrix4(uProjectionLocation, true, ref projection);
            }
        }

        GL.Viewport(this.ClientRectangle);
    }

首先,

float ratio = windowWidth / windowHeight;

很可能没有按照您在编写此代码时的实际想法进行操作。 windowWidthwindowHeight 都是 int 类型,所以 / 将在结果转换为 float 之前执行整数除法。结果,ratio 大部分时间都恰好为 1。有时可能为 0(如果高度 > 宽度)。偶尔可能有 2 个(在某些宽屏设置上)。很可能,您想要的是更像这样的东西:

float ratio = (float)windowWidth / (float)windowHeight;

然而,即便如此,当您计算矩阵时

Matrix4 projection = Matrix4.CreateOrthographic(ratio * 10, ratio * 10, -1, 1);

您使用 ratio 缩放宽度和高度,这意味着无论最终比率是多少,您最终都会再次得到方形视口的矩阵(因为宽度和高度相同)。最有可能的是,例如,您希望仅使用纵横比

缩放宽度
Matrix4 projection = Matrix4.CreateOrthographic(ratio * 10, 10, -1, 1);

除此之外,请注意大部分实际功能是如何复制到 if 语句的两个分支中的。另请注意,您只需跳过宽度和高度相等的情况。你可以重写这一整堆 ifs,例如,像这样

float ratio = (float)ClientRectangle.Width / (float)Math.Max(ClientRectangle.Height, 1);
Matrix4 projection = Matrix4.CreateOrthographic(ratio * 10, 10, -1, 1);
GL.UniformMatrix4(uProjectionLocation, true, ref projection);