bresenham画圆算法java
时间: 2023-12-06 14:38:42 浏览: 100
以下是用Java实现Bresenham算法画整圆的代码:
```java
import java.awt.*;
import javax.swing.*;
public class BresenhamCircle extends JPanel {
private int centerX, centerY, radius;
private int[][] grid;
public BresenhamCircle(int centerX, int centerY, int radius) {
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
grid = new int[2 * radius + 1][2 * radius + 1];
setPreferredSize(new Dimension(2 * radius + 1, 2 * radius + 1));
setBackground(Color.WHITE);
calculatePoints();
}
private void calculatePoints() {
int x = 0, y = radius, d = 3 - 2 * radius;
while (x <= y) {
plotPoints(x, y);
if (d < 0) {
d = d + 4 * x + 6;
} else {
d = d + 4 * (x - y) + 10;
y--;
}
x++;
}
}
private void plotPoints(int x, int y) {
grid[centerX + x][centerY + y] = 1;
grid[centerX + x][centerY - y] = 1;
grid[centerX - x][centerY + y] = 1;
grid[centerX - x][centerY - y] = 1;
grid[centerX + y][centerY + x] = 1;
grid[centerX + y][centerY - x] = 1;
grid[centerX - y][centerY + x] = 1;
grid[centerX - y][centerY - x] = 1;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int cellWidth = width / (2 * radius + 1);
int cellHeight = height / (2 * radius + 1);
for (int i = 0; i <= 2 * radius; i++) {
for (int j = 0; j <= 2 * radius; j++) {
if (grid[i][j] == 1) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
g.setColor(Color.GRAY);
g.drawRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bresenham Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BresenhamCircle circle = new BresenhamCircle(100, 100, 50);
frame.getContentPane().add(circle);
frame.pack();
frame.setVisible(true);
}
}
```
阅读全文