确定是否在Java中旋转的矩形内鼠标滑动(AWT,swing)

时间:2013-02-08 20:25:38

标签: java swing affinetransform

如果矩形已经旋转,我在确定如何确定是否在矩形内部单击了鼠标点击事件时遇到了一些麻烦。

假设我有一个像这样简单的MouseAdapter。它只是打印出一条声明,如果mousePressed实际上在矩形内,我们就会触及矩形。

MouseAdapter mAdapter = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        int xPos = e.getX();
        int yPos = e.getY();
        if(xPos >= rect.x && xPos <= rect.x + rect.width && yPos >= rect.y && yPos <= rect.y + rect.height) {
            System.out.println("HIT INSIDE RECTANGLE");
        }
    }
};

我的问题来自旋转矩形时。上面的if语句显然不考虑旋转,所以在旋转矩形后,我的命中测试失败。对于旋转,我在paint()函数中做了这么简单的事情:

class drawRect {

    Rectangle rect = new Rectangle();

    ...

    public void paint(Graphics g) {
        Graphcis2D g2 = (Graphics2D) g;
        AffineTransform old = g2.getTransform();
        g.rotate(Math.toRadians(90), rect.x, rect.y); 
        g2.draw(rect);
        g2.setTransform(old);
    }
}

这只是一些快速伪代码,所以你们可以理解我想要做的事情。所以请不要担心语法和所有这些。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您也可以将旋转应用于鼠标坐标。干编码:

MouseAdapter mAdapter = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        // Create the same transform as used for drawing the rectangle
        AffineTransform t = new AffineTransform();
        t.rotate(Math.toRadians(90), rect.x, rect.y);
        Point2D tp = t.inverseTransform(e.getPoint());

        if(rect.contains(tp)) {
            System.out.println("HIT INSIDE RECTANGLE");
        }
    }
};