Java动画:旋转图像
问题描述:
我有一个非常简单的Java动画任务。我需要创建一个基本的“财富之轮小程序”。基本上显示的是一个*和一个按钮。当按下该按钮时,我希望它选择一个随机的度数(例如在720-3600的范围内)并旋转许多度数的*。然后,我将使用一些逻辑将该学位数转换为货币价值。我的问题是在动画中,如何让图像以恒定的速度旋转x度?有没有摆动功能?非常感谢您的帮助,除此之外,我现在不需要了解关于Java动画的其他任何信息。Java动画:旋转图像
答
我打算假设您了解如何旋转图像一次。如果你不这样做,你可以通过快速的谷歌搜索找到。
你需要的是一个为你旋转它的后台进程。它的工作原理是这样的:
/**
* 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
}
}
+0
这看起来真棒,我曾经在SO得到最好的答案之一见。我只是有点困惑这部分实现以及如何,以及你的意思是旋转一次图像? – 2011-02-19 06:16:45
也http://*.com/questions/3420651 – trashgod 2011-02-19 03:29:51