有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从多个较小的图像构建图像

因此,我正在制作这个冒险/进展游戏,对于字体,我使用精灵表中的瓷砖(每个瓷砖都是字母),我将用于许多不同的用途,我不明白为什么我的程序返回的是黑色图像,而不是由较小的图像(每个图像都包含字母)生成的图像。当我返回scaleImage图像时,程序会工作,但只返回一个字母。应该发生的是,我将单词分割成一个字母,然后使用缓冲图像图形2D从精灵表中获取匹配的字母,该部分工作,但当我将其绘制到缓冲图像时,它返回一个黑色图像

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);

共 (1) 个答案

  1. # 1 楼答案

    经过一段时间的研究,我发现字母没有显示的原因是它们是黑色的,而BuffereImage的背景也是黑色的。因此,这些字母显示出来了,但由于背景的原因,它们“看不见”