【问题标题】:Java: draw an Ellipse2D starting from the coordinates of the two fociJava:从两个焦点的坐标开始绘制一个Ellipse2D
【发布时间】:2014-12-26 15:09:20
【问题描述】:

假设我知道左上角的坐标以及 a 和 b 轴,Ellipse2D 允许我绘制一个椭圆。相反,我有两个焦点的坐标,以及每个点到两个焦点的 l 距离。如何从两个焦点的坐标开始创建对应的Ellipse2D?

【问题讨论】:

  • by 1.阅读Oracle教程??? - 绘制几何图元,2.在这里搜索java + Ellipse2D
  • @mKorbel 我认为这涉及更多。但是它缺少信息,但我 1. 完全不确定如何基于焦点创建 Ellipse2D,以及 2. 当焦点没有相同的 y 坐标时这是“不可能的”(Ellipse2D 无法存储一个 rotated 椭圆本身 - 你需要一个 Ellipse2D 和一个旋转角度,或者将其表示为一般 Shape)
  • 事实上,Oracle 文档没有考虑到这一点,实际上 Ellipse2D 类假定并支持两个轴平行于 X 和 Y 的椭圆。这就是我问这个问题的原因。

标签: java awt ellipse drawellipse


【解决方案1】:

这是我的代码。它创建一个以原点 (0,0) 为中心的大小合适的椭圆。然后它使用 AffineTransform 将椭圆平移和旋转到适当的位置。返回定义所需椭圆的 Shape 。 变量名来自 http://math.tutorvista.com/geometry/ellipse-equation.html 希望它对你有用。

   #import java.awt.geom.*;

   /* Create an ellipse given foci and distance. 
     (x1,y1) and (x2,y2) are  foci. semimajor axis (the sum of distances
     that define the ellipse) is *dist*.
     See
     for meaning of vars
   */
    public Shape makeEllipse (
        float x1, float y1, float x2, float y2, float dist
    )
    {
        // Create foci points
        Point2D f1 = new Point2D.Float (x1, y1);
        Point2D f2 = new Point2D.Float (x2, y2);

        // Calculate ellipse characteristics
        double a = dist / 2.0;
        double c = f1.distance (f2) / 2.0;
        // If 'dist' is smaller than the distance between foci, 
        // the ellipse is invalid
        if (a < c)
           die ("Invalid semimajor axis length"); 
        double b = Math.sqrt (a * a - c * c);

        Point2D centre = 
            new Point2D.Float ((x1 + x2) / 2.0, (y1 + y2) / 2.0);

        // Create a transform to rotate and translate the ellipse
        double theta = Math.atan2 (y2 - y1, x2 - x1);
        AffineTransform trans = new AffineTransform();
        trans.translate (centre.getX(), centre.getY());
        trans.rotate(theta);

        // Create an ellipse with correct size but origin at centre 
        Ellipse2D tmpEllipse = new Ellipse2D.Double (-a, -b, 2 * a, 2 * b);

        // Translate and rotate it to where it should be
        Shape ellipse = trans.createTransformedShape (tmpEllipse);

        return ellipse;
    } 

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多