我从ludum dare(minicraft)中看了一下Notch的代码,我注意到他使用:
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();所以我做了一个简单的测试程序,我注意到与之前使用的方法相比,我的性能下降了很多。使用这种方法,只要绘制一个完全白色的屏幕,我就可以获得800fps,而当我绘制测试图像时,我得到的帧数超过1200,这似乎有点奇怪。即使我不在pixels[]上声明任何东西,只保留默认的一个,它仍然是800fps。我想知道有没有人能给我解释一下原因。这是我写的测试代码,我使用fps得到我的fps:
public class Test extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
private boolean running = false;
public final int HEIGHT = 300;
public final int WIDTH = 360;
private final int SCALE = 3;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private BufferedImage testImage;
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
JFrame frame;
public Test(){
Dimension size = new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
frame = new JFrame();
this.frame.setResizable(false);
this.setPreferredSize(size);
this.setMaximumSize(size);
this.setMinimumSize(size);
this.frame.add(this);
this.frame.pack();
this.frame.setLocationRelativeTo(null);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setFocusable(true);
this.frame.setVisible(true);
try {
testImage = ImageIO.read(new File("res/test.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0; i < pixels.length; i++){
pixels[i] = 0xffffff;
}
running = true;
}
public void run() {
while(running){
render();
}
}
private void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//Draw stuff
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(testImage, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String args[]){
Test test = new Test();
test.run();
}}
我简单地用image替换了testImage。感谢所有人,祝节日快乐
编辑:我注意到简单地调用int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();会大大降低应用程序的运行速度。有人能给我解释一下为什么吗?我需要处理像素还是别的什么吗?谢谢
发布于 2014-09-10 22:24:57
据我所知,BufferedImages在幕后被视为VolatileImages。这意味着他们得到了一个巨大的硬件加速提升。这是因为图像被直接复制到显卡的内存中,从而实现快速绘图。
当您想要访问像素矩阵时,图像将被放入常规RAM中,并从那里访问,因此导致显着减慢。
实际上,如果您禁用JVM中的所有硬件加速,则绘制白色图像的速度将最快。
如果您希望有效地更新屏幕,请将setIgnoreRepaint(true)应用于您的窗口,并且只绘制已更改的屏幕部分。
https://stackoverflow.com/questions/20777500
复制相似问题