转换后如何获得绝对坐标 [英] How to get absolute coordinates after transformation

查看:158
本文介绍了转换后如何获得绝对坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制这样的Java 2D:

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.

推荐答案

获取 AffineTransform /javase/1.4.2/docs/api/java/awt/Graphics2D.html\"rel =nofollow> Graphics2D 对象并使用 transform(src, dst)方法转到屏幕坐标(你可以为任何一点做这个)。如果您想要椭圆的路径,可以使用 Ellipse2D.getPathIterator(AffineTransform at) - 它返回 PathIterator

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);
}

这篇关于转换后如何获得绝对坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆