实验一 1.2
This commit is contained in:
80
lab1/2.cpp
Normal file
80
lab1/2.cpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <GL/glut.h>
|
||||
|
||||
// 窗口宽度和高度
|
||||
const int WIDTH = 640;
|
||||
const int HEIGHT = 480;
|
||||
|
||||
void drawDDALine(int x1, int y1, int x2, int y2) {
|
||||
float x = x1;
|
||||
float y = y1;
|
||||
|
||||
// 计算差值
|
||||
int dx = x2 - x1;
|
||||
int dy = y2 - y1;
|
||||
|
||||
// 确定步数,取 dx 和 dy 中绝对值较大的那个
|
||||
int steps = std::abs(dx) > std::abs(dy) ? std::abs(dx) : std::abs(dy);
|
||||
|
||||
// 计算每一步的增量
|
||||
float xIncrement = (float)dx / steps;
|
||||
float yIncrement = (float)dy / steps;
|
||||
|
||||
// 开始绘制点
|
||||
glBegin(GL_POINTS);
|
||||
glVertex2i((int)round(x), (int)round(y)); // 绘制起点
|
||||
|
||||
for (int k = 0; k < steps; k++) {
|
||||
x += xIncrement;
|
||||
y += yIncrement;
|
||||
// 将浮点坐标四舍五入转换为整数像素坐标
|
||||
std::cout << (int)round(x) << ", " << (int)round(y)<<"\n";
|
||||
glVertex2i((int)round(x), (int)round(y));
|
||||
}
|
||||
glEnd();
|
||||
}
|
||||
|
||||
// 显示回调函数
|
||||
void display() {
|
||||
drawDDALine(0, 0, 50, 20);
|
||||
glFlush();
|
||||
}
|
||||
|
||||
// 初始化 OpenGL 设置
|
||||
void init() {
|
||||
// 设置背景颜色为白色
|
||||
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
|
||||
|
||||
// 设置投影矩阵为 2D 正交投影
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity();
|
||||
// 定义可视区域,左下角(0,0),右上角(WIDTH, HEIGHT)
|
||||
gluOrtho2D(0.0, WIDTH, 0.0, HEIGHT);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// 初始化 GLUT
|
||||
glutInit(&argc, argv);
|
||||
|
||||
// 设置显示模式:单缓冲、RGB 颜色模式
|
||||
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
|
||||
|
||||
// 设置窗口大小和位置
|
||||
glutInitWindowSize(WIDTH, HEIGHT);
|
||||
glutInitWindowPosition(100, 100);
|
||||
|
||||
// 创建窗口
|
||||
glutCreateWindow("DDA算法");
|
||||
|
||||
// 注册回调函数
|
||||
glutDisplayFunc(display);
|
||||
|
||||
// 初始化设置
|
||||
init();
|
||||
|
||||
// 进入主循环
|
||||
glutMainLoop();
|
||||
|
||||
return 0;
|
||||
}
|
||||
BIN
lab1/2.exe
Normal file
BIN
lab1/2.exe
Normal file
Binary file not shown.
Reference in New Issue
Block a user