计算机图形学-基于OpenGL的绘制直线及图形变换练习
本实验集成开发环境为vs2013,基于OpenGL。
实验内容
- 在窗口中绘制一条曲线,参数曲线:
-
x(t)=200+50∗(2∗cos(2∗π∗t)−cos(4∗π∗t))
-
y(t)=150+50∗(2∗sin(2∗π∗t)−sin(4∗π∗t))
-
0≤t≤1
-
- 对该曲线如下变换:平移一个距离使曲线移到屏幕中心,缩小到原来的0.5倍,旋转60度。
预备知识
在曲线上按参数t进行for循环200次,每次将ti=i/200代入参数方程计算出一个点。
将这些点连成折线段即可。
glBegin(GL_LINE_STRIP);
OpenGL中的变换:
平移:glTranslatef(dx,dy,dz);
旋转:glRotatef(angle, x, y, z);
缩放:glScalef(sx, sy, sz);
实验代码
#include <GL/glut.h>
#include <cstdio>
#include <cmath>
const GLfloat Pi = 3.1415926536f;
//定义点集
struct data{
GLfloat x;
GLfloat y;
}Point[201];
void init() //初始化函数
{
glClearColor(1.0, 1.0, 1.0, 0.0); //设置背景颜色
glMatrixMode(GL_PROJECTION); // 设置投影参数
gluOrtho2D(0.0, 600.0, 0.0, 400.0); // 设置场景的大小
}
void mydisplay() //显示函数
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0); //设置线条颜色
glPointSize(2); //设置点的大小
glTranslatef(100.0f, 0.0f, 0.0f); //平移图形
glScalef(0.5f, 0.5f, 0.0f); //缩小图像0.5倍
glRotatef(60.0f, 1.0f, 0.0f, 0.0f); //沿x轴旋转60度
glBegin(GL_LINE_STRIP);
for (int i = 1; i <= 200; i++)
{
GLfloat t = i / 200.0;
Point[i].x = 200.0 + 50.0 * (2.0 * cos(2.0 * Pi*t) - cos(4.0 * Pi*t)); //参数曲线
Point[i].y = 150.0 + 50.0 * (2.0 * sin(2.0 * Pi*t) - sin(4.0 * Pi*t)); //参数曲线
glVertex2i(Point[i].x, Point[i].y); //绘制曲线
}
glEnd();
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(400, 400);
glutCreateWindow("绘制曲线及图形变换");
init();
glutDisplayFunc(&mydisplay);
glutMainLoop();
return 0;
}