bresenham算法画圆java代码
时间: 2023-10-22 16:20:56 浏览: 45
以下是使用Bresenham算法画圆的Java代码:
```
import java.awt.*;
import javax.swing.*;
public class BresenhamCircle extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = 100;
int x = 0;
int y = radius;
int d = 3 - 2 * radius;
while (y >= x) {
drawCircle(g2, centerX, centerY, x, y);
x++;
if (d > 0) {
y--;
d = d + 4 * (x - y) + 10;
} else {
d = d + 4 * x + 6;
}
drawCircle(g2, centerX, centerY, x, y);
}
}
private void drawCircle(Graphics2D g2, int centerX, int centerY, int x, int y) {
g2.fillRect(centerX + x, centerY + y, 1, 1);
g2.fillRect(centerX - x, centerY + y, 1, 1);
g2.fillRect(centerX + x, centerY - y, 1, 1);
g2.fillRect(centerX - x, centerY - y, 1, 1);
g2.fillRect(centerX + y, centerY + x, 1, 1);
g2.fillRect(centerX - y, centerY + x, 1, 1);
g2.fillRect(centerX + y, centerY - x, 1, 1);
g2.fillRect(centerX - y, centerY - x, 1, 1);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bresenham Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
BresenhamCircle panel = new BresenhamCircle();
frame.setContentPane(panel);
frame.setVisible(true);
}
}
```
这段代码使用了Java的Graphics2D类来绘制圆,算法部分使用了Bresenham算法。在paintComponent()方法中,我们首先获取了组件的中心点和半径,然后使用while循环来依次计算每个点的坐标并绘制。在drawCircle()方法中,我们通过填充矩形的方式来绘制圆。最后,在main()方法中,我们创建了一个JFrame并将BresenhamCircle实例设置为其内容面板。运行该程序将会显示一个绘制了圆的窗口。