我正在制作一个关于太空物理学的应用,所以我用轨道做了很多 . 当然,我遇到 Ellipse2D.Double
在屏幕上绘制我的轨道 .
每当我的JPanel刷新时,我使用Ellipse2D绘制一个物体的轨道,并使用不同的方法绘制身体本身 .
基本上,我发现当数字变得非常大时(无论是轨道大小变大还是可视化变焦很远),主体和Ellipse2D的位置都不对齐 .
我使用从极坐标到直角坐标的转换来计算身体的位置,并将Ellipse2D的数学运算保留到 geom
包 .
看一下这段代码示例 . 这是我可以制作的最独立的问题版本,因为圆的比例必须非常大:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EllipseDemo extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.add(new EllipseDemo());
frame.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// These values allow for a very zoomed in view of a piece of the circle
BigDecimal[] circleCenter = { new BigDecimal(-262842.5), new BigDecimal(-93212.8) };
BigDecimal circleRadius = new BigDecimal(279081.3);
// Draw the circle at the given center, with the given width and height
// x = centerx - radius, y = centery - radius, w = h = radius * 2
g2d.draw(new Ellipse2D.Double(circleCenter[0].subtract(circleRadius).doubleValue(),
circleCenter[1].subtract(circleRadius).doubleValue(), circleRadius.multiply(new BigDecimal(2)).doubleValue(),
circleRadius.multiply(new BigDecimal(2)).doubleValue()));
// Get a rectangular conversion of a point on the circle at this angle
BigDecimal angle = new BigDecimal(0.34117696217);
BigDecimal[] rectangular = convertPolarToRectangular(new BigDecimal[] {
circleRadius, angle });
// Draw a line from the center of the circle to the point
g2d.draw(new Line2D.Double(circleCenter[0].doubleValue(), circleCenter[1].doubleValue(),
circleCenter[0].add(rectangular[0]).doubleValue(), circleCenter[1]
.add(rectangular[1]).doubleValue()));
}
public BigDecimal[] convertPolarToRectangular(BigDecimal[] polar) {
BigDecimal radius = polar[0];
BigDecimal angle = polar[1];
BigDecimal x = radius.multiply(new BigDecimal(Math.cos(angle.doubleValue())));
BigDecimal y = radius.multiply(new BigDecimal(Math.sin(angle.doubleValue())));
return new BigDecimal[] { x, y };
}
}
上面的代码基本上在很远的半径范围内在屏幕上绘制一个圆圈 . 我选择了尺寸,以便在小窗口中看到一块圆圈 .
然后它从圆的中心绘制一条线到窗口中可见的圆上的一个点:我选择了一个在窗口上可见的角度,并使用几何将该角度和圆的半径转换为直角坐标 .
这是程序显示的内容:
请注意,该线实际上并未触及椭圆 . 现在,我决定必须弄清楚这是我计算的点还是椭圆不正确 . 我在计算器上做了数学计算,发现线条正确,椭圆不正确:
考虑到计算器可能没错,我被认为是Ellipse2D没有正确绘制 . 但是,我尝试了很多其他角度,这就是我发现的模式:
这让我相信计算在某种程度上是错误的 .
这就是我的问题 . 我应该使用Ellipse2D以外的东西吗?也许Ellipse2D不够准确?我在我的代码示例中使用了BigDecimals因为我认为它会给我更多的精确度 - 这是错误的方法吗?我的最终目标是能够以特定角度计算椭圆上一个点的矩形位置 .
提前致谢 .
1 回答
您会看到此错误,因为Ellipse2D近似为四条三次曲线 . 要确保只看一下定义形状边框的路径迭代器:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/awt/geom/EllipseIterator.java#187
为了提高质量,我们应该通过更高数量的三次曲线来近似椭圆 . 这是一个标准java实现的扩展,具有可变数量的段:
以下是如何在代码中使用它而不是标准代码(我在这里使用100个段):