我正在尝试增加调整应用程序窗口大小的功能,而不会导致窗口内容同时伸展。我已经尝试过更改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);
}
答案 0 :(得分:2)
首先,
float ratio = windowWidth / windowHeight;
在编写此代码时,很可能并没有真正想到的。 windowWidth
和windowHeight
均为int
类型,因此/
将执行整数除法,然后将结果转换为float
。结果,ratio
将花费大部分时间精确地为1。有时可能是0(如果height> width)。有时可能是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);