0

我正在编写一个 2D 程序。在我的paintComponent我创建了一个弧。

public class Board extends Panel{

    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D graphics2d = (Graphics2D)g;
        int x = MouseInfo.getPointerInfo().getLocation().x;//set mouses current position
        int y = MouseInfo.getPointerInfo().getLocation().y;

        graphics2d.setStroke(wideStroke);
        graphics2d.draw(new Arc2D.Double(200, 200, 100, 100, ?, 180, Arc2D.OPEN));

    }
}

在我的主要内容中,我使用 aThread来更新图表。的位置?是起始角度。每次我改变它时,圆弧都会像半个车轮一样绕一圈移动。是否可以让弧线运动跟随鼠标?例如? = 270

在此处输入图像描述

我将如何做到这一点?(对不起我的绘画技巧不好!)

4

1 回答 1

1

所以基于来自Java 2d 方向鼠标点旋转的信息

我们需要两件事。我们需要锚点(即圆弧的中心点)和目标点,即鼠标点。

使用 a MouseMotionListener,可以监控组件内的鼠标移动

// Reference to the last known position of the mouse...
private Point mousePoint;
//....
addMouseMotionListener(new MouseAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        mousePoint = e.getPoint();                    
        repaint();                    
    }                
});

接下来我们需要计算这两点之间的角度......

if (mousePoint != null) {
    // This represents the anchor point, in this case, 
    // the centre of the component...
    int x = width / 2;
    int y = height / 2;

    // This is the difference between the anchor point
    // and the mouse.  Its important that this is done
    // within the local coordinate space of the component,
    // this means either the MouseMotionListener needs to
    // be registered to the component itself (preferably)
    // or the mouse coordinates need to be converted into
    // local coordinate space
    int deltaX = mousePoint.x - x;
    int deltaY = mousePoint.y - y;

    // Calculate the angle...
    // This is our "0" or start angle..
    rotation = -Math.atan2(deltaX, deltaY);
    rotation = Math.toDegrees(rotation) + 180;
}

从这里开始,您需要减去 90 度,这将给出您的弧的起始角度,然后使用 180 度的范围。

于 2014-04-30T22:39:05.357 回答