我试图在二维数组上的一组坐标之间画一条线。在弄清楚如何只从用户生成的字符串中取出数字并将它们分配给向量之后,我在二维数组上创建线条时遇到了麻烦。虽然我能够绘制坐标的2个点,但我无法在它们之间绘制线条。
请在下面找到评论代码:
vector<int> results;
char *board[10][20];
int main()
{
string userInput;
getline(cin,userInput); //takes in user input
for(int i = 0; i < userInput.length(); i++) //checks each character
{
if(isdigit(userInput[i])) //if a character is a digit
{
int value = userInput[i] - 48; //for ascii
results.push_back(value); //add to vector
if(isdigit(userInput[i + 1])) //then check the next value (max of 2 digits)
{
results[i] = 10 * (userInput[i + 1]); //if it is, create the original number
}
}
}
for (int i =0; i < results.size(); i++)
{
cout << results.at(i) << endl;
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 20; j++)
{
board[i][j] = " "; //setting up board with white spaces
}
cout << endl;
}
board[results.at(1)][results.at(0)] = "1"; //first coordinate
board[results.at(3)][results.at(2)] = "2"; //second coordinate
int dx = results.at(2) - results.at(0);
int dy = results.at(3) - results.at(1);
int y;
int D;
//for (int x = results.at(0); x < results.at(2); x++) // line drawing algorithm
//{
// y = results.at(1) + (dy) * (x - results.at(0))/(dx);
// board[x][y] = "X"; //set up line of X's
//}
D = 2*dy - dx;
y = results.at(1);
for (int x = results.at(0) + 1; x < results.at(2); x++) // Bresenhams
{
if (D < 0)
{
y = y+1;
board[x][y] = "X";
D = D + (2*dy-2*dx);
}
else
{
board[x][y];
D = D+(2*dy);
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 20; j++)
{
cout << board[i][j]; //display the board
}
cout << endl;
}
system("PAUSE");
return 0;
}
如您所见,程序获取用户的坐标,并检查字符串中的值。如果他们是数字;将它们添加到矢量中。然后我用白色空间设置了电路板,因此可以在之后绘制线条。
我尝试了两种类型的算法。即使第一个产生某种线条(虽然正确),但第二条线条却没有做任何事情。我密切关注维基百科页面,所以我不确定发生了什么。希望评论的代码帮助,任何帮助将不胜感激。谢谢!
编辑:问题: http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm http://en.wikipedia.org/wiki/Line_drawing_algorithm