用Bresenham算法绘制多边形的算法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Bresenham算法绘制多边形的算法相关的知识,希望对你有一定的参考价值。
敬请回复,谢谢!
参考技术A void SetPixel( int x, int y )glBegin( GL_POINTS );
glColor3f(
(double)( y + alpha * 10 ) / ( height + alpha * 10 ),
(double)( x + y ) / ( width + height ),
(double)( x + alpha * 10 ) / ( height + alpha * 10 )
);
glVertex2i( x, y );
glEnd( );
// Bresenham line algorithm
void MyLine( int xs, int ys, int xe, int ye )
// Write your code here
int dx, dy, x, y, p, k;
dx = abs( xe - xs );
dy = abs( ye - ys );
k = ( xe - xs ) * ( ye - ys );
if ( dx >= dy )
p = 2 * dy - dx;
if ( xs < xe ) x = xs; y = ys;
else y = ye; x = xe; xe = xs;
while ( x < xe )
SetPixel( x, y );
++x;
if ( p < 0 )
p += 2 * dy;
else
if ( k > 0 ) ++y;
else --y;
p += 2 * dy - 2 * dx;
else
p = 2 * dx - dy;
if ( ys < ye ) x = xs; y = ys;
else y = ye; x = xe; ye = ys;
while ( y < ye )
SetPixel( x, y );
++y;
if ( p < 0 )
p += 2 * dx;
else
if ( k > 0 ) ++x;
else --x;
p += 2 * dx - 2 * dy;
Bresenham算法是划线段的,多画几条就成多边形了。
MyLine四个参数分别是起止点的x y坐标。本回答被提问者采纳
Bresenham 线算法错误
【中文标题】Bresenham 线算法错误【英文标题】:Error with Bresenham's line algorithm 【发布时间】:2015-08-28 19:24:01 【问题描述】:我正在尝试用星号 (*) 填充矩阵以绘制 Bresenham 的线,但是当我打印出矩阵仅填充一颗星的东西时,我不知道出了什么问题。语言是Java
public class PtLine extends VectorObject // inherites from another class
private int bx;
private int by;
private int delX;
private int delY;
public PtLine(int id,int x,int y,int bx,int by)
super(id,x,y);
this.bx = bx;
this.by = by;
this.delX = this.bx-x;
this.delY = this.by-y;
public void draw ( char [][] matrix ) // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i==bx;i++)
if(D > 0)
j+=1;
matrix[i][j]='*';
D = D + (2*delY-2*delX);
else
matrix[i][j]='*';
D = D + (2*delY);
下面的代码是当我试图打印出矩阵时
class Question3
public static void main ( String args [] )
char[][] matrix = new char[20][20];
for (int y = 0; y < 20; y++)
for (int x = 0; x < 20; x++)
matrix[y][x] = ' ';
PtLine n = new PtLine(6,6,6,13,13);
n.draw(matrix);
for (int y = 0; y < 20; y++)
for (int x = 0; x < 20; x++)
System.out.print(matrix[x][y]);
System.out.println();
【问题讨论】:
【参考方案1】:您可能必须将i==bx
更改为i!=bx
:
public void draw ( char [][] matrix ) // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i!=bx;i++) // here
...
for
循环在此条件为真时继续。在您的代码循环中,在第一次迭代之前立即结束,因为这个条件是假的。
【讨论】:
以上是关于用Bresenham算法绘制多边形的算法的主要内容,如果未能解决你的问题,请参考以下文章