如何解决我的中点算法有什么问题?
我刚刚开始学习处理,但有一些我无法解决的问题。我希望有人可以帮助我。这应该画线,我可以用 mousepressed()
选择起点和终点,但我在尝试实施之前失败了。
//int x1,x2,y1,y2;
void setup() {
size(640,480);
}
void draw() {
midpoint(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,100);
它会画它
midpoint(100,0);
它什么也没画。
如果我交换点坐标应该画相同的线,如果坐标相同则画一个点。
解决方法
在 Bresenham 的中点线算法中,您必须小心绘制的线的梯度,您描述的基本算法仅适用于 0 和 1 之间的梯度。为了处理更陡峭的梯度 (m > 1
或m < -1
),则需要切换x
和y
值的角色,因此必须步入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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。