我的中点算法有什么问题

  • 本文关键字:问题 算法 processing
  • 更新时间 :
  • 英文 :


我刚开始学习处理,有一些问题我无法解决。我希望有人能帮助我。这应该为我选择mousePressed()的起点和终点画出界限,但我在尝试实现之前失败了。

//int x1, x2, y1, y2;
void setup() {
size(640, 480);
}
void draw() {
midpoint(0, 0, 100, 100);
}
//void mousePressed() {
//  pmouseX =x1;
//  pmouseY =y1;
//  mouseX =x2;
//  mouseY =y2;
//}
void midpoint(int x1, int y1, int x2, int y2) {
int dx, dy, d, x, y;
dx = x2-x1;
dy = y2-y1;
d = 2*dy-dx;
x = x1;
y = y1;
for (int i = 1; i <dx; i++) {
point(x, y);
if (d>0) {
y++;
d+=2*(dy-dx);
} else {
d+=2*dy;
}
x++;
}
}

我的问题是它不会总是划清界限。例如

midpoint(0,0,100,100);

它将绘制

midpoint(100,100,0,0);

它什么也没画。

如果我交换点的坐标,它应该画同一条线,或者如果坐标相同,它应该绘制一个点。

在Bresenham的中点线算法中,您必须小心绘制的线的梯度,您描述的基本算法仅适用于0和1之间的梯度。为了处理更陡的梯度(m > 1m < -1(,您必须切换xy值的角色,因此您必须介入y,然后计算x。同样为了处理负步骤,只需切换点顺序。

void midpoint(int x1, int y1, int x2, int y2) {
// Is gradient of line greater than 1
boolean steep = abs(y2-y1) > abs(x2-x1);
int temp;
if (steep) {   // If gradient > 1
// Swap roles of x and y components to step in y instead
temp = y1;
y1 = x1;
x1 = temp;
temp = y2;
y2 = x2;
x2 = temp;
}
if (x2 < x1) {  
// Swap points such that step in x is positive
temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
// Change in x and y which are now both positive
int dx = x2 - x1;
int dy = abs(y2 - y1);
// Step in y
int sy = y2 > y1 ? 1 : -1;
int y = y1;
// Decision variable
int d = 2*dy-dx;
// Small step in x
for (int x=x1; x<=x2; x++) {
// Depending on gradient plot x and y
if (steep) {
point(y, x);
} else {
point(x, y);
}
// Update decision parameter
if (d>0) {
y += sy;
d+=2*(dy-dx);
}else{
d+=2*dy;
}
}
}

最新更新