Tony Merrit
Tony Merrit

Reputation: 171

How to get absolute coordinates after transformation

I am drawing Java 2D stuff like this:

g2.translate( getWidth() / 2, getHeight() / 2 );
g2.rotate( angle );
g2.draw( new Ellipse2D.Double( -1, -1, 1, 1 ) );

Now I want to kow the coordinates of the ellipse on my sceen. Any idea how to get it? So I need the conversion from logical to physical space.

Upvotes: 2

Views: 3320

Answers (3)

dacwe
dacwe

Reputation: 43504

Get the AffineTransform from the Graphics2D object and use the transform(src, dst) method to go to screen coordinates (you can do this for any point). If you want the path of the ellipse you can use Ellipse2D.getPathIterator(AffineTransform at) - it returns a PathIterator.

This example gets the center point of the ellipse on the screen:

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");


    frame.add(new JComponent() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g;

            g2.translate( getWidth() / 2, getHeight() / 2 );
            g2.rotate(Math.PI); // some angle

            Ellipse2D.Double ellipse = new Ellipse2D.Double( -10, -10, 10, 10 );
            g2.draw(ellipse);

            Point2D c = new Point2D.Double(
                    ellipse.getCenterX(), 
                    ellipse.getCenterY());

            AffineTransform at = g2.getTransform();
            Point2D screenPoint = at.transform(c, new Point2D.Double());

            System.out.println(screenPoint);
        }
    });

    frame.setSize(400, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

Upvotes: 1

Bala R
Bala R

Reputation: 109017

If you create a reference to the ellipse

g2.translate( getWidth() / 2, getHeight() / 2 );
g2.rotate( angle );
Ellipse2D.Double ellipse = new Ellipse2D.Double( -1, -1, 1, 1 );
g2.draw( ellipse );

for x g2.getTransform().getTranslateX() + ellipse.getX()

and for y g2.getTransform().getTranslateY() + ellipse.getY()

Upvotes: 0

Bernd Elkemann
Bernd Elkemann

Reputation: 23560

Its easy, there are many methods, you dont find them in Ellipse2D however.

You can use its parent RectangularShape, then depending on how accurate you want it to be you can subtract accounting for the curvature.

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/geom/RectangularShape.html

Upvotes: 0

Related Questions