用Java小程序和Bresenham算法绘制圆心坐标为(200,100),圆的半径为100的圆形,其中其中左上圆弧为黑色,左下圆弧为青色,右下圆弧为红色,右上圆弧为灰色
时间: 2024-06-12 16:08:12 浏览: 154
java实现Bresenham算法画圆
4星 · 用户满意度95%
下面是Java小程序代码:
```
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BresenhamCircle extends JPanel {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 500;
private static final int HEIGHT = 400;
private static final int RADIUS = 100;
private static final int CENTER_X = 200;
private static final int CENTER_Y = 100;
private static final Color[] COLORS = { Color.BLACK, Color.CYAN, Color.RED, Color.GRAY };
public void paint(Graphics g) {
for (int i = 0; i < 4; i++) {
drawArc(g, i);
}
}
private void drawArc(Graphics g, int colorIndex) {
int x = 0;
int y = RADIUS;
int d = 3 - 2 * RADIUS;
while (x <= y) {
plot(g, x, y, colorIndex);
if (d < 0) {
d = d + 4 * x + 6;
} else {
d = d + 4 * (x - y) + 10;
y--;
}
x++;
}
}
private void plot(Graphics g, int x, int y, int colorIndex) {
int[] xs = { CENTER_X + x, CENTER_X + x, CENTER_X - x, CENTER_X - x };
int[] ys = { CENTER_Y + y, CENTER_Y - y, CENTER_Y + y, CENTER_Y - y };
g.setColor(COLORS[colorIndex]);
g.fillPolygon(xs, ys, 4);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bresenham Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.add(new BresenhamCircle());
frame.setVisible(true);
}
}
```
程序使用了Bresenham算法绘制圆形,并根据颜色索引绘制了四个圆弧。其中,plot()方法用于绘制一个四边形,表示圆弧的一个像素点。程序中使用了Java的图形库Graphics实现绘制。运行程序后,可以看到绘制的圆形如下图所示:
![Bresenham Circle](https://i.imgur.com/9FzJ7I0.png)
阅读全文