Java Swing 实现正n边形各边绘制直径为d的圆的错位Bug排查
给定 n 个直径为
d的圆,我需要生成边长为d的正n边形,并在正n边形的每条边上绘制一个圆。
我在开发某款应用时遇到了该问题。
已知正N边形的每条边长度为a时,其外接圆半径计算公式如下:

我的代码
游戏窗体(Game Frame)
import javax.swing.JFrame; public class gameFrame extends JFrame{ static int width = 400; static int height = 400; public static void main(String[] args) { gameFrame frame = new gameFrame(); gamePanel panel = new gamePanel(); frame.add(panel); frame.setTitle("Tutorial"); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(true); panel.initializeList(); panel.fpsTimer.start(); } }
游戏面板(Game Panel)
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Arc2D; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.Timer; public class gamePanel extends JPanel{ static ArrayList<Point2D> coordinates = new ArrayList<Point2D>(); static int d = 20; Timer fpsTimer = new Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { repaint(); } }); public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; // 遍历坐标列表绘制圆形 for(Point2D point : coordinates) { g2d.setColor(Color.BLACK); Shape circle = new Arc2D.Double(point.x, point.y, d, d, 0 , 360, Arc2D.CHORD); g2d.fill(circle); } } public void initializeList() { Point2D center = new Point2D(0,0); int n = 15; // 正多边形的边数 float alpha = 360/ n; // 正多边形拆分出的每个三角形的圆心角 float angle = 0; // 循环中使用的累计旋转角 float side = d; // 正多边形期望的单条边长度 float radius = (float) (side / (2*Math.sin(Math.PI / n))); // 外接圆半径公式:R = a / (2*sin(PI/n)) // 校验外接圆半径是否超出窗体范围 if(!(radius >= gameFrame.width || radius >= gameFrame.height)) { // 正多边形的中心坐标 center.x = (gameFrame.width)/2; center.y = (gameFrame.height)/2; for(int i = 0 ; i < n ; i++) { coordinates.add(new Point2D((center.x + Math.sin(angle)*radius), (center.y -Math.cos(angle)*radius))); angle += alpha; } } } }
Point2D类(简化实现)
public class Point2D { double x; double y; public Point2D(double x , double y) { this.x = x; this.y = y; } }
运行效果与问题描述
对于上述设置的n=15、d=20,运行输出效果如下:

部分圆出现重叠。奇怪的是,将GamePanel类的initializeList()方法中的angle += alpha修改为angle += alpha+0.295;后,反而得到了预期效果:

当n=14时,输出的错位问题更严重:

我已经在这个Bug上花费了大量时间,请问有人知道问题出在哪里吗?
内容的提问来源于stack exchange,提问作者hexaquark
相关产品推荐
相关产品推荐

