我有作业,ASCII 线图抽屉。我必须将图形打印到文件中。 Bresenham 线算法的所有算法都有函数 SetPixel ( x, y );在循环中。此函数必须按 x 和 y 打印像素。 NCurses 库是在 Windows 控制台上打印的理想解决方案,但我必须打印到 file.txt 中。我认为 Ncurses 只在窗口控制台上打印。我的问题:如何在此代码中实现用于打印到文件中的 SetPixel 函数? :
void Line( const float x1, const float y1, const float x2, const float y2, const Color& color )
{
// Bresenham's line algorithm
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++)
{
if(steep)
{
SetPixel(y,x, color);
}
else
{
SetPixel(x,y, color);
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
最佳答案
要将其保存到文件中,您需要在将数据写入文件之前进行一些初始计算。我建议您创建一个数据结构(也许是一个数组)来跟踪每个“像素”。例如,您可以声明
char graph[100][100];
graph
的每个元素要么是一个空格,要么是一个'X'
。使用 Bresenham 的直线算法计算 graph
中应设置为 'X'
的元素,然后将数组写入文件。
关于c++ - Bresenham 的直线算法。文件是否存在 ncurses 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055908/