Bresenham 算法使用 Java应用程序 绘制直线的示例代码
时间: 2023-05-24 10:01:52 浏览: 129
以下是 Bresenham 算法使用 Java 应用程序绘制直线的示例代码:
```java
import java.awt.*;
import javax.swing.*;
public class Bresenham extends JFrame {
public Bresenham() {
super("Bresenham's Line Drawing Algorithm");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
// Set the color to blue
g.setColor(Color.blue);
// Call the drawLine() method using Bresenham algorithm
drawLine(50, 50, 200, 200, g);
}
private void drawLine(int x1, int y1, int x2, int y2, Graphics g) {
int dx = Math.abs(x2 - x1);
int dy = Math.abs(y2 - y1);
int sx, sy;
if (x1 < x2) {
sx = 1;
} else {
sx = -1;
}
if (y1 < y2) {
sy = 1;
} else {
sy = -1;
}
int err = dx - dy;
while (true) {
g.drawLine(x1, y1, x1, y1);
if (x1 == x2 && y1 == y2) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x1 += sx;
}
if (e2 < dx) {
err += dx;
y1 += sy;
}
}
}
public static void main(String[] args) {
Bresenham demo = new Bresenham();
demo.setVisible(true);
}
}
```
该程序使用 Bresenham 算法绘制一条直线,将颜色设置为蓝色,并在窗口中绘制出来。
阅读全文