Java动画:旋转图像

4
我有一个很简单的Java动画任务。我需要创建一个基本的“幸运轮Applet”。基本上会显示一个轮子和一个按钮。当按下该按钮时,我希望它选择一个随机角度(例如在720-3600范围内)并旋转该角度数。然后,我将使用一些逻辑将该角度数转换为货币价值。我的问题在于动画中,如何使图像以恒定的速度旋转x个角度?是否有一个Swing函数可以实现这个功能?非常感谢您的帮助,我现在不需要了解Java动画方面的其他内容。

请参见http://stackoverflow.com/questions/3420651。 - trashgod
1个回答

7
我假设您已经知道如何旋转一张图片。如果不知道,您可以通过快速的谷歌搜索找到。
您需要一个后台进程来为您旋转它。它的工作原理如下:
/**
 * Warning - this class is UNSYNCHRONIZED!
 */
public class RotatableImage {
    Image image;
    float currentDegrees;

    public RotateableImage(Image image) {
        this.image = image;
        this.currentDegrees = 0.0f;
        this.remainingDegrees = 0.0f;
    }

    public void paintOn(Graphics g) {
        //put your code to rotate the image once in here, using current degrees as your rotation
    }

    public void spin(float additionalDegrees) {
        setSpin(currentDegrees + additionalDegrees);
    }

    public void setSpin(float newDegrees) {
        currentDegrees += additionalDegrees;
        while(currentDegrees < 0f) currentDegrees += 360f;
        while(currentDegrees >= 360f) currentDegrees -= 360f;
    }

}

public class ImageSpinner implements Runnable {
    RotateableImage image;
    final float totalDegrees;
    float degrees;
    float speed; // in degrees per second
    public ImageSpinner(RotatableImage image, float degrees, float speed) {
        this.image = image;
        this.degrees = degrees;
        this.totalDegrees = degrees;
        this.speed = speed;
    }

    public void run() {
        // assume about 40 frames per second, and that the it doesn't matter if it isn't exact
        int fps = 40;
        while(Math.abs(degrees) > Math.abs(speed / fps)) { // how close is the degrees to 0? 
            float degreesToRotate = speed / fps;
            image.spin(degreesToRotate);
            degrees -= degreesToRotate;
            /* sleep will always wait at least 1000 / fps before recalcing
               but you have no guarantee that it won't take forever! If you absolutely
               require better timing, this isn't the solution for you */
            try { Thread.sleep(1000 / fps); } catch(InterruptedException e) { /* swallow */ }
        }
        image.setSpin(totalDegrees); // this might need to be 360 - totalDegrees, not sure
    }

}

这看起来很棒,是我在SO上得到的最好的答案之一。我只是有点困惑要实现哪个部分以及如何实现,还有您所说的旋转图像一次是什么意思? - Sam Stern
在其他地方找到了答案,但选择你是因为你是这里最好的,谢谢。 - Sam Stern

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接