DDA直线扫描算法:
void CDraw::DDALine(CDC* pDC,int x1,int y1,int x2,int y2,COLORREF color)
{
double dx,dy,e,x,y;
dx = x2-x1;
dy = y2-y1;
e = (fabs(dx) > fabs(dy))? fabs(dx):fabs(dy);
dx /= e;
dy /= e;
x = x1;
y = y1;
for (int i=1; i<=e; i++)
{
pDC->SetPixel((int)(x+0.5),(int)(y+0.5),color);
x += dx;
y += dy;
}
}
中点画线算法:
void CDraw::MIdpointLine(CDC* pDC,int x0,int y0,int x1,int y1,COLORREF color)
{
int a,b,delta1,delta2,d,x,y;
if (x0 == x1)//传入的端点坐标x值相等
{
if (y0 < y1)
{
for (int i=y0; i<=y1; i++)
{
pDC->SetPixel(x0,i,color);
}
}
else
{
for (int i=y1; i<=y0; i++)
{
pDC->SetPixel(x0,i,color);
}
}
return ;
}
//斜率判断,斜率大于1,则m为false,否则为true.
BOOL m = (fabs(y1-y0) <= fabs(x1-x0));
//如果传入的x0大于x1,将坐标值互换
if (x0>x1)
{
d = x0;
x0 = x1;
x1 = d;
d = y0;
y0 = y1;
y1 = d;
}
a = y0 - y1;
b = x1 - x0;
x = x0;
y = y0;
pDC->SetPixel(x,y,color);
if (m)
{
if (y0 < y1) //第一种情况y值递增
{
d = 2*a + b;
delta1 = 2*a;
delta2 = 2*(a+b);
while (x < x1)
{
if (d < 0)
{
x++;
y++;
d += delta2;
}
else
{
x++;
d += delta1;
}
pDC->SetPixel(x,y,color);
}
}
else //第三种情况,y值递减
{
d = 2*a - b;
delta1 = 2*a;
delta2 = 2*(a - b);
while (x < x1)
{
if (d < 0)
{
x++;
d += delta1;
}
else
{
x++;
d += delta2;
}
pDC->SetPixel(x,y,color);
}
}
}
else //斜率绝对值大于1
{
if (y0 <= y1) //第二种情况,y值递增
{
d = a + 2*b;
delta1 = 2*b;
delta2 = 2*(a + b);
while (y < y1)
{
if (d < 0)
{
y++;
d += delta1;
}
else
{
y++;
x++;
d += delta2;
}
pDC->SetPixel(x,y,color);
}
}
else //第四种情况,y值递减
{
d = a - 2*b;
delta1 = -2*b;
delta2 = 2*(a - b);
while (y > y1)
{
if (d < 0)
{
y--;
x++;
d += delta2;
}
else
{
y--;
d += delta1;
}
pDC->SetPixel(x,y,color);
}
}
}
}