如何循环浏览不同的图像,Java
我的代码由g.drawimg;用于在屏幕上绘制图像;。有没有一种方法可以让图像在不同的图像中循环而不是静止?我尝试过.gif文件,但它们没有;不行。这是我的密码:如何循环浏览不同的图像,Java,java,animation,textures,Java,Animation,Textures,我的代码由g.drawimg;用于在屏幕上绘制图像;。有没有一种方法可以让图像在不同的图像中循环而不是静止?我尝试过.gif文件,但它们没有;不行。这是我的密码: static BufferedImage img = null; { try { img = ImageIO.read(new File("assets/textures/bird.png")); } catch (IOException e) { System.out.println(
static BufferedImage img = null;
{
try {
img = ImageIO.read(new File("assets/textures/bird.png"));
} catch (IOException e) {
System.out.println(e.getMessage();
}
}
有没有办法为纹理设置动画?您可以创建一个小类来完成此操作:
public class SimpleImageLoop {
private final BufferedImage[] frames;
private int currentFrame;
public SimpleImageLoop(BufferedImage[] frames) {
this.frames = frames;
this.currentFrame = 0;
}
/**
* Moves the loop to the next frame.
* If we are on the last frame, this loops back to the first
*/
public void nextFrame() {
this.currentFrame++;
if (this.currentFrame >= frames.length) {
this.currentFrame = 0;
}
}
/**
* Draws the current frame on the provided graphics context
*/
public void draw(Graphics g) {
g.draw(this.frames[this.currentFrame];
}
}
然后需要一个简单的动画循环来通过更新和绘制调用:
如果需要平滑结果,可以包括其他参数,如应执行的循环次数、帧的持续时间等。可以使用not java.util.Timer或ScheduledExecutorService,除非您准备使用invokeLater在AWT事件调度线程中更改映像,这只是示例代码,它可以有一些地方需要调整。到底是什么问题?任何异常,或者仅仅是不正确的行为?我对编程非常陌生,所以我几乎不知道我在做什么,这里有一些代码我没有做,我只是在做。我将如何实现它呢?我做了一个示例Bird,基于您的Bird类:我更改了一些内容以使类更好。希望以此为基础,你可以达到你想要的。很可能你需要做一些改变,使它与你的其他课程一起工作。你有特定的堆栈跟踪吗?不知道这意味着什么。正如我说的,我是个初学者
final SimpleImageLoop imageLoop = new SimpleImageLoop(frames);
while (true) {
imageLoop.nextFrame();
imageLoop.draw(g);
}