【问题标题】:How to rotate an image towards cursor location?如何将图像旋转到光标位置?
【发布时间】:2021-12-23 05:44:07
【问题描述】:

我正在尝试将图像旋转到光标位置(旋转应该是从图像的中心向光标位置旋转)

    public void rotateImg(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g.create();

        int cursorX = MouseInfo.getPointerInfo().getLocation().x - panel.getLocationOnScreen().x; // Mouse pos
        int cursorY = MouseInfo.getPointerInfo().getLocation().y - panel.getLocationOnScreen().y;
        Point center = new Point(x+size/2,y+size/2); //Image center (x,y are the player's coordinates)
        double dx = cursorX - center.getX();
        double dy =cursorY - center.getY();

        System.out.println(Math.toDegrees(Math.atan2(dx,dy)));

        g2.rotate(Math.toRadians(Math.atan2(dy,dx)),center.x,center.y);
        g2.drawImage(playerImage,x,y,size,size, null);
    }

这个函数在一个线程中运行,所以它永远不会停止,我检查了光标位置是否正在更新(它们是),角度也是如此,但是当我运行它时它几乎不旋转,甚至不能旋转 45 度

先谢谢了!

【问题讨论】:

    标签: java swing rotation position graphics2d


    【解决方案1】:

    试过这个:

    public void rotateImg(Graphics g)
        {
            double degrees;
            Graphics2D g2 = (Graphics2D)g.create();
    
            Point center = new Point(x+size/2,y+size/2); //Image center (x,y are the player's coordinates)
            int cursorX = MouseInfo.getPointerInfo().getLocation().x - panel.getLocationOnScreen().x; // Mouse pos
            int cursorY = MouseInfo.getPointerInfo().getLocation().y - panel.getLocationOnScreen().y;
            double dx = cursorX - center.getX();
            double dy = cursorY - center.getY();
    
            degrees = Math.toDegrees(Math.atan2(dy,dx))+90;
    
            g2.rotate(Math.toRadians(degrees),center.x,center.y);
            g2.drawImage(playerImage,x,y,size,size, null);
        }
    

    成功了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多