bresenham 画直线算法

void lineBresenham(int nStartX, int nStartY, int nEndX, int nEndY) { int dx = abs(nEndX - nStartX); int dy = abs(nEndY - nStartY); if( dx == 0 ) { if( nStartY > nEndY ) { int temp; temp = nEndY; nEndY = nStartY; nStartY = temp; } for( int y = nStartY; y <= nEndY; ++y ) setPixel(nStartX, y); return; } if( dy == 0 ) { if( nStartX > nEndX ) { int temp; temp = nEndX; nEndX = nStartX; nStartX = temp; } for( int x = nStartX; x <= nEndX; ++x ) setPixel(x, nStartY); return; } if( dx == dy ) { float fSlope = (float)(nEndY - nStartY) / (float)(nEndX - nStartX); if( nStartX < nEndX ) { if( fSlope > 0.0f ) { int x = nStartX; int y = nStartY; for( ; x <= nEndX; ++x, ++y ) { setPixel(x, y); } } else { int x = nStartX; int y = nStartY; for( ; x <= nEndX; ++x, --y ) { setPixel(x, y); } } } else { if( fSlope > 0.0f ) { int x = nStartX; int y = nStartY; for( ; x >= nEndX; --x, --y ) { setPixel(x, y); } } else { int x = nStartX; int y = nStartY; for( ; x >= nEndX; --x, ++y ) { setPixel(x, y); } } } return; } float fSlope = (float)(nEndY - nStartY) / (float)(nEndX - nStartX); if( 0.0f < fSlope && fSlope < 1.0f ) { int p = 2 * dy - dx; int twoDy = 2 * dy; int twoDyMinusDx = 2 * (dy - dx); int x; int y; if( nStartX > nEndX ) { x = nEndX; y = nEndY; nEndX = nStartX; nEndY = nStartY; } else { x = nStartX; y = nStartY; } setPixel(x, y); while(x < nEndX) { x++; if( p < 0 ) { p += twoDy; } else { y++; p += twoDyMinusDx; } setPixel(x, y); } if( y != nEndY ) setPixel(nEndX, nEndY); } else if( fSlope > 1.0f ) { int p = 2 * dx - dy; int twoDx = 2 * dx; int twoDxMinusDy = 2 * (dx - dy); int x; int y; if( nStartY > nEndY ) { x = nEndX; y = nEndY; nEndX = nStartX; nEndY = nStartY; } else { x = nStartX; y = nStartY; } setPixel(x, y); while(y < nEndY) { y++; if( p < 0 ) { p += twoDx; } else { x++; p += twoDxMinusDy; } setPixel(x, y); } if( x != nEndX ) setPixel(nEndX, nEndY); } else if( 0.0f > fSlope && fSlope > -1.0f ) { int p = 2 * dy - dx; int twoDy = 2 * dy; int twoDyMinusDx = 2 * (dy - dx); int x; int y; if( nStartX < nEndX ) { x = nEndX; y = nEndY; nEndX = nStartX; nEndY = nStartY; } else { x = nStartX; y = nStartY; } setPixel(x, y); while(x > nEndX) { x--; if( p < 0 ) { p += twoDy; } else { y++; p += twoDyMinusDx; } setPixel(x, y); } if( y != nEndY ) setPixel(nEndX, nEndY); } else //if( fSlope < -1.0f ) { int p = 2 * dx - dy; int twoDx = 2 * dx; int twoDxMinusDy = 2 * (dx - dy); int x; int y; if( nStartY > nEndY ) { x = nEndX; y = nEndY; nEndX = nStartX; nEndY = nStartY; } else { x = nStartX; y = nStartY; } setPixel(x, y); while(y < nEndY) { y++; if( p < 0 ) { p += twoDx; } else { x--; p += twoDxMinusDy; } setPixel(x, y); } if( x != nEndX ) setPixel(nEndX, nEndY); } }

你可能感兴趣的:(算法,float)