我正在尝试在Java中实现DDA算法来画一条线。线光栅器实现一个接口。然后我在名为 Canva
的类中调用 rasterizeLine
函数。线栅格化成功获得 x 和 y 点。不会抛出任何错误,但是算法必须存在一些逻辑问题,因为没有绘制线。你能帮我找到逻辑错误吗?
接口
package rasterops;
import rasterdata.RasterImage;
public interface LineRasterizer<PixelType> {
RasterImage<PixelType> rasterizeLine(RasterImage<PixelType> img,
double x1, double y1, double x2, double y2,
PixelType value);
}
线光栅器
package rasterops;
import rasterdata.RasterImage;
public class LineRasterizerDDA<PixelType> implements LineRasterizer <PixelType> {
@Override
public RasterImage<PixelType> rasterizeLine(RasterImage<PixelType> img, double x1, double y1, double x2, double y2, PixelType value) {
double dy = y2-y1;
double dx = x2-x1;
double k = dy/dx;
double y = y1;
RasterImage<PixelType> result = img;
for( double x = x1; x <= x2; x++ ){
result = result.withPixel((int)x, (int)Math.round(y), value);
y = y1 + k;
}
return result;
}
}
Canva - 调用函数
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
previousX = e.getX();
previousY = e.getY();
}
});
panel.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
final double startX = previousX / (panel.getWidth() - 1.0); //k zamysleni: proc 1.0 a ne 1?
final double startY = 1 - previousY / (panel.getHeight() - 1.0);
final double endX = e.getX() / (panel.getWidth() - 1.0);
final double endY = 1 - e.getY() / (panel.getHeight() - 1.0);
clear(); // zkuste zakomentovat
rasterImage = liner.rasterizeLine(rasterImage,
startX, startY, endX, endY,
0xffff00);
panel.repaint();
}
});
这一行:
y = y1 + k;
不断将相同的值分配给y
,因为y1
和k
没有改变。
示例输出,在 (0,0) 和 (10, 10) 之间绘制线条:
O..........
.OOOOOOOOOO
...........
...........
...........
...........
...........
...........
...........
...........
...........
您可能意味着:
y = y + k;
或y += k;
.
示例输出,在 (0,0) 和 (10, 10) 之间绘制线条:
O..........
.O.........
..O........
...O.......
....O......
.....O.....
......O....
.......O...
........O..
.........O.
..........O