我有一个非常简单的Java动画任务。我需要创建一个基本的“财富小轮子”。基本上将显示的是轮子和按钮。当按下该按钮时,我希望它选择一个随机的度数(例如在720-3600范围内)并旋转许多度数的轮子。然后我将使用一些逻辑将该度数转换为货币值。我的问题在于动画,如何让图像以恒定的速度旋转x度?那有摆动功能吗?非常感谢帮助,除此之外,我现在不需要了解任何有关Java动画的内容。
答案 0 :(得分:6)
我将假设您了解如何旋转图像一次。如果不这样做,您可以通过快速谷歌搜索找到它。
您需要的是一个为您旋转它的后台进程。它的工作原理如下:
/**
* 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
}
}