为什么我现有的图像不能绘制到屏幕上?

Why won't my existing image draw to the screen?

基本上是这样,我试图从项目中的源文件加载图像,但每当我 运行 代码时,什么也没有发生。

任何人都可以阐明我哪里出错了,也许可能如何让它正确绘制?

代码如下:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


public class EnterTile extends Tile {

public EnterTile() {
    setTile();
}

public void setTile() {

    try {
        BufferedImage img = ImageIO.read(new File("res\BrokenFenceSwamp.gif"));
        Graphics g = img.getGraphics();
        g.drawImage(img, 1000, 1000, 8, 8, null);
    } catch (IOException e) {
        System.out.println("Error " + e);
    }
}

public static void main(String args[]) {
    EnterTile enterTile = new EnterTile();


}



}

感谢您花时间阅读本文。

要正确加载图像,您需要:

  1. res 文件夹(存储图像的位置)标记为资源文件夹。
  2. 调用ImageIO的read()方法时,需要传入一个URL。为此,您需要使用 {className}.class.getResource({path}) (你的情况 ImageIO.read(EnterTile.class.getResource("/BrokenFenceSwamp.gif"));

要绘制图像,您需要指定位置。 例如canvas 如果您使用的是 awt 库。 您可以尝试这样的操作:

public class Main {
    public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("Image Test");
        frame.setSize(400, 800);
        frame.setVisible(true);
        frame.setFocusable(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);

        Canvas canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(400, 800));
        canvas.setMaximumSize(new Dimension(400, 800));
        canvas.setMinimumSize(new Dimension(400, 800));

        frame.add(canvas);
        frame.pack();

        canvas.createBufferStrategy(2);    
        BufferStrategy bs = canvas.getBufferStrategy();

        Graphics g = bs.getDrawGraphics();
        g.clearRect(0, 0, 400, 800);

        String path = "/BrokenFenceSwamp.gif";
        BufferedImage image = ImageIO.read(Main.class.getResource(path));

        g.drawImage(image, 0, 0, null);

        bs.show();
        g.dispose();
    }
}

获取图像的图形是一种能够在图像上绘图的工具:

    BufferedImage img = ImageIO.read(new File("res\BrokenFenceSwamp.gif"));

    Graphics g = img.getGraphics();
    g.drawString(img, 100, 100, "Hello World!");
    g.dispose();

    ImageIO.write(new File("res/TitledBFS.gif"));

它不在屏幕上绘制。 Graphics 可以是内存(此处)、屏幕或打印机。

要在屏幕上绘图,可以制作一个没有标题和边框的 full-screen window,然后在其背景上绘制图像。

这需要熟悉 swing 或更新的 JavaFX。