【发布时间】:2021-02-04 14:45:18
【问题描述】:
所以我正在制作这个冒险/进度游戏,我使用 spriteSheet 中的拼贴(每个拼贴都是一个字母)的字体,我将用于许多不同的目的,但我不知道为什么我的程序是返回黑色图像而不是由较小图像(每个图像包含一个字母)构建的图像。该程序在我返回 scaledImage 图像时工作,但只返回一个字母。应该发生的事情是我将单词分成一个字母并使用 BufferedImage 和 Graphics2D 从 spriteSheet 中获取匹配的字母,这部分有效,但是当我绘制时它到缓冲图像,它返回一个黑色的图像。
BufferedImage spriteSheet;
String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", " " };
public ImageIcon getWord(String word, int x, int size) throws IOException {
String tempLetter;
try {
spriteSheet = ImageIO.read(new File("img/SpriteSheet.png"));
} catch (IOException e) {
e.printStackTrace();
}
Image testImage = null;
BufferedImage bi = new BufferedImage(size * word.length(), size, BufferedImage.TYPE_INT_RGB);
Graphics2D wordImage = bi.createGraphics();
Image subImage;
Image scaledImage;
for (int l = 0; l < word.length(); l++) {
tempLetter = word.substring(l, l + 1);
for (int i = 0; i < alphabet.length; i++) {
if (tempLetter.equalsIgnoreCase(alphabet[i])) {
subImage = spriteSheet.getSubimage(2 + (2 * i) + (i * 200), 2, 200, 200);
scaledImage = subImage.getScaledInstance(size, size, Image.SCALE_DEFAULT);
wordImage.drawImage(scaledImage, l*size, 0, null);
testImage = scaledImage;
} else {
continue;
}
}
}
wordImage.dispose();
File wordFile = new File("img/word.png");
ImageIO.write(bi, "png", wordFile);
ImageIcon ic = new ImageIcon("img/word.png");
wordFile.delete();
return ic;
}
这就是我调用方法的方式:
JButton play = new JButton();
play.setBounds(300, 300, 600, 150);
play.setIcon(sc.getWord("play", 600, 150));
p.add(play);
f.add(p);
【问题讨论】:
-
为什么将图像写入文件然后再读取?你在用 IOException 做什么?
-
@RealSkeptic 我找不到其他方法。
-
new ImageIcon(bi)怎么样? -
@RealSkeptic 仍然无法正常工作。
-
@RealSkeptic 我发现了错误......所以字母是黑色的,背景也是黑色的,所以它们正在显示但我看不到它们。