我正在尝试在 Java 中创建斜坡。我可以使用 DrawLine 函数来创建完美的斜坡,但我不想使用它,而是要创建自己的函数。问题在于点之间存在间隙。
import java.applet.Applet;
import java.awt.Graphics;
public class slope extends Applet{
public void drawLine(int x1, int y1, int x2, int y2, Graphics g) {
double m = (y2 - y1) / (double)(x2-x1);
double y = y1;
for (int x =x1; x < x2; x++) {
drawPoint(x,(int)y,g);
y +=m;
}
}
public void paint(Graphics g) {
drawLine(20, 10, 300, 700, g); //has spaces between the dots
g.drawLine(20, 10, 300, 700); //this is perfect
}
private void drawPoint(int x, int y, Graphics g) {
g.drawLine(x, y, x, y);
}
}
x
或y
。 - Maarten Bodewesm
大于1,那么显然会有间隙,因此您需要在y
上添加1/m
到x
。如果您注意到还需要处理负值,则可以获得额外的分数。 - Maarten Bodewes