如何将相同的缓冲图像再次加载到面板上,而不必再次创建相同的缓冲图像?

时间:2019-05-04 17:30:53

标签: java image bufferedimage

如果这是我的照片,

private BufferedImage LVL140;

try

{        

LVL140 = ImageIO.read(new File("SplendorIm/LVL140.png"));

} catch (IOException e)

{

e.printStackTrace();

}

g.drawImage(LVL140,1050,0,null);

如何将相同的缓冲图像再次加载到面板上而不必再次创建相同的缓冲图像?

1 个答案:

答案 0 :(得分:0)

加载图像后,请在其中使用while {}和其中的Thread.sleep()的{​​{1}}。

这里有个例子:

g.drawImage()

请注意,您可以使用public class DrawSystem extends JPanel implements Runnable { private int width, height; private BufferedImage img; private boolean running; private Graphics2D g; //Theses lines could be in a configuration, but let's do it here private void int FPS = 60; private long targetTime = 1000 / FPS; private BufferedImage LVL140; public DrawSystem(Dimension dimensions) { width = (int) dimensions.getWidth(); height = (int) dimensions.getHeight(); //here's your LVL140 image LVL140 = ImageIO.read(new File("SplendorIm/LVL140.png")); } //you just have to start the thred with (variable).start(); @Override public void run() { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) img.getGraphics(); running = true; long start; long elapsed; long wait; while(running) { start = System.nanoTime(); draw(); drawToScreen(); elapsed = System.nanoTime() - start; wait = targetTime - elapsed / 1000000; if(wait > 0) { try{ Thread.sleep(wait); } catch(Exception e) { e.printStackTrace(); } } } } //Draw pixels of "LVL140" on "img". You can draw others things without impact "LVL140" thanks to this private void draw() { g.drawImage(LVL140, 0, 0, null); } //draw pixels of "img" on the JPanel. private void drawToScreen() { Graphics g2 = getGraphics(); if(g2 != null) { g2.drawImage(img, 0, 0, width, height, null); g2.dispose(); } } } ,然后从那里启动Thread,但是不要自欺欺人,这是您在Java中迈出的第一步。

Juste创建一个addNotify(),添加JFrame并执行:

DrawSystem

如您所见,您只需创建一次BufferedImage,然后在DrawSystem sys = new DrawSystem(new Dimension(1000, 500)); <(your JFrame)>.add(sys); Thread th = new Thread(sys); //call the `run()` method th.start(); 方法中多次使用它。 希望对您有帮助。