OPENGL如何改变窗口大小保持图形的纵横比,原理是什么?
问题的关键在于设置裁剪区域的纵横比与视口的纵横比一致。
设置视口大小:
[cpp] view plain copy
<span style="font-size:18px;">glViewport(GLint x,GLint y,GLsizei w,GLsizei h);</span>
(x,y)是视口距离窗口左下角的位置,(w,h)是视口的宽度和高度。
设置二维观察函数:
[cpp] view plain copy
glOrtho2D(GLdouble left,GLdouble right,GLdouble bottom,GL double top);
锁定纵横比,注意这里为什么要加一个判断语句。比如当窗口的宽大于高时(w>h),裁剪区域只能设置将高扩大即:(-15.0/ratio,15.0/ratio),而不能设置将宽缩小(这样会使图像在w方向的部分显示不出来)
[html] view plain copy
glViewport(0,0,w,h);
GLfloat ratio=(GLfloat)w/(GLfloat)h;
if(w<=h)//保持形状不变
gluOrtho2D(-15.0,15.0,-15.0/ratio,15.0/ratio);
else
gluOrtho2D(-15.0*ratio,15.0*ratio,-15.0,15.0);
具体代码:
[cpp] view plain copy
#include <stdlib.h>
#include <GL/glut.h>
GLfloat v[3][3]={{-10.0,0.0,0.0},{10.0,0.0,0.0},{0.0,10.0,0.0}};
int num=5;
void reshape(GLsizei w,GLsizei h)
{
GLfloat ratio=(GLfloat)w/(GLfloat)h;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)//保持形状不变
gluOrtho2D(-15.0,15.0,-15.0/ratio,15.0/ratio);
else
gluOrtho2D(-15.0*ratio,15.0*ratio,-15.0,15.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void triangle(GLfloat* a,GLfloat* b,GLfloat* c)
{
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
}
void divide_triangle(GLfloat* a,GLfloat* b,GLfloat* c,int n)
{
GLfloat ab[3],ac[3],bc[3];
if(n>0)
{
for(int j=0;j<3;j++)
{
ab[j]=(a[j]+b[j])/2;
ac[j]=(a[j]+c[j])/2;
bc[j]=(b[j]+c[j])/2;
}
divide_triangle(a,ab,ac,n-1);
divide_triangle(ab,b,bc,n-1);
divide_triangle(ac,bc,c,n-1);
}
else triangle(a,b,c);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
divide_triangle(v[0],v[1],v[2],num);
glEnd();
glFlush();
}
void myInit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(0.0,1.0,0.0);
glViewport(0,0,500,500);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-15.0,15.0,-15.0,15.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Sierpinski");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
myInit();
glutMainLoop();
}
视口和视景体,当视口的纵横比和视景体的纵横比相同的时候,改变窗口大小,图像才不会变形;例如:控制视口大小为:glViewprot(0,0,400,200);则其纵横比为2那么控制视景体的参数为:gluPerspective(fovy,2,near,far);可以了控制视景体还有其他函数,原理是一样的opengl编程指南有详细解释。
2023-08-15 广告