用Bresenham算法画直线C++代码
时间: 2024-11-06 22:19:48 浏览: 16
Bresenham算法是一种古老的计算机图形学技术,用于快速近似绘制直线条纹,尤其适用于像素艺术和离散坐标系。以下是使用C++实现的简单Bresenham算法来画一条从(x0, y0)到(x1, y1)的直线的基本代码:
```cpp
#include <iostream>
#include <vector>
// 计算下一个像素的位置
int next(int x, int y, int dx, int dy) {
return (abs(dy) > abs(dx)) ? (x + (y > y0) * dx) : (y + (x > x0) * dy);
}
void bresenham_line(int x0, int y0, int x1, int y1) {
int dx = std::abs(x1 - x0);
int dy = std::abs(y1 - y0);
bool steep = (dy > dx);
if (steep) {
std::swap(x0, y0);
std::swap(x1, y1);
}
int x = x0, y = y0;
for (int i = 0; i <= dx; ++i) {
if (steep) {
std::cout << "P(" << y << ", " << x << ")";
} else {
std::cout << "P(" << x << ", " << y << ")";
}
if ((dx == 0 && dy == 1) || (i % dy == 0)) {
if (steep) {
std::cout << "\n";
} else {
x++;
}
}
y += dy;
}
}
int main() {
int x0, y0, x1, y1;
// 输入两点坐标
std::cout << "Enter the starting coordinates (x0, y0): ";
std::cin >> x0 >> y0;
std::cout << "Enter the ending coordinates (x1, y1): ";
std::cin >> x1 >> y1;
bresenham_line(x0, y0, x1, y1);
return 0;
}
```
阅读全文