我已经测试了所有的情况,一条线可以是
函数工作,但我希望它的审查,如是否有溢出,等等。
// Draw line using DDA Algorithm
void Graphics::DrawLine( int x1, int y1, int x2, int y2, Color&color )
{
float xdiff = x1-x2;
float ydiff = y1-y2;
int slope = 1;
if ( y1 == y2 )
{
slope = 0;
}
else if ( x1 == x2 )
{
slope = 2; // vertical lines have no slopes...
}
else
{
slope = (int)xdiff/ydiff;
}
if ( slope <= 1 )
{
int startx = 0;
int endx = 0;
if ( x1 > x2 )
{
startx = x2;
endx = x1;
}
else
{
startx = x1;
endx = x2;
}
float y = y1; // initial value
for(int x = startx; x <= endx; x++)
{
y += slope;
DrawPixel(x, (int)abs(y), color);
}
}
else if ( slope > 1 )
{
float x = x1; // initial value
for(int y = y1;y <= y2; y++)
{
x += 1/slope;
DrawPixel((int)x, y, color);
}
}
}发布于 2014-07-16 15:24:46
以下是当前算法中的一些缺陷。
xdiff的大小很大,那么x1-x2将有一个舍入错误,y变量也是如此。slope无缘无故地设置为1,然后立即重新初始化为其他内容。slope被限制为整数。2是不可能的。有些斜坡大于2,但不是垂直线。slope = (int)xdiff/ydiff;中,浇铸的优先级高于除法,因此这将首先将xdiff抛给int,如果xdiff > MAXINT溢出,则丢弃分数部分(如果有),然后将该int除以ydiff。这个实际坡度的概率很小。startx和endx无缘无故地初始化为0,然后立即重新初始化为其他东西。slope添加到y (或1/slope到x)时,舍入错误将累积。abs(y)的理由是什么?如果y更改了范围内的符号,这将导致行中的扭结。同样适用于x。发布于 2013-09-30 08:54:54
这毫无意义。slope必须是int,如0、1、2、3、4、…但是垂直线被看作是一条斜率线2?这怎么准确呢?
https://codereview.stackexchange.com/questions/31982
复制相似问题