我试图使用缓冲图像从精灵表中渲染精灵,但我无法弄清楚为什么我的代码无法正常工作,即使我正在调用来自班级的形象?
代码:
package com.game.src.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private BufferedImage spriteSheet = null;
boolean sprite = false;
private BufferedImage sprite;
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/astronaut_sprite1.png");
}catch(IOException e){
e.printStackTrace();
}
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
if(sprite == true){
g.drawImage(sprite, 0, 0, getWidth(), getHeight(), this);
System.out.println("True");
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_1){
sprite = true;
}
}
public static void main(String args[]){
Game game = new Game();
public BufferedImage getSpriteSheet(){
return spriteSheet;
}
}
我正在调用的类(精灵)是:
package com.game.src.main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class sprite{
private double x;
private double y;
private BufferedImage sprite;
public sprite(x, y, Game game){
SpriteSheet ss = new SpriteSheet(game.getSpriteSheet());
sprite = ss.grabImage(3, 3, 32, 32);
}
BufferedImageLoader:
package com.game.src.main;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
image = ImageIO.read(getClass().getResourceAsStream(path));
return image;
}
}
答案 0 :(得分:1)
使用ImageIO.read(new File("/astronaut_sprite1.png"));
代替spriteSheet = loader.loadImage("/astronaut_sprite1.png");
您的文件夹结构:
-src
--com
---m14x
----game
-----BufferedImageLoader.java
-----Game.java
-----SpriteSheet.java
-res
---sprite_sheet.png
你的BufferedImageLoader类:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
System.out.println("PATH = " + path);
File file = new File(path);
if (file.exists()) {
// First, make sure the path exists
System.out.println("File exists!");
}
if (file.isDirectory()) {
// This will tell you if it is a directory
System.out.println("File is a directory!");
}
if (file.isFile()) {
// Similarly, this will tell you if it's a file
System.out.println("File has a path!");
}
System.out.println("Trying to load image:");
image = ImageIO.read(new File(path));
//image = ImageIO.read(getClass().getResource(path));
System.out.println("Image path found. Returning...");
return image;
}
}