1 void drawLine(int x1,int y1,int x2,int y2,UINT color) 2 { 3 int dx = x2 - x1; 4 int dy = y2 - y1; 5 int ux = ((dx > 0) << 1) - 1;//x的增量方向,取1或-1 6 int uy = ((dy > 0) << 1) - 1;//y的增量方向,取1或-1 7 8 dx = abs(dx); 9 dy = abs(dy); 10 11 int x = x1, y = y1; 12 int eps = 0; 13 14 //线段靠近x轴 15 if(dx > dy) 16 { 17 for (x = x1;x != x2 + ux;x += ux) 18 { 19 setPixels(x, y, color); 20 eps += dy; 21 if((eps << 1) >= dx) 22 { 23 y += uy; 24 eps -= dx; 25 } 26 } 27 } 28 else 29 { 30 for (y = y1; y != y2 + uy; y += uy) 31 { 32 setPixels(x, y, color); 33 eps += dx; 34 if ((eps << 1) >= dy) 35 { 36 x += ux; 37 eps -= dy; 38 } 39 } 40 } 41 }