Files
Computer-Graphics-Lab/lab1/2.cpp
2026-04-05 20:34:27 +08:00

80 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#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;
}