【发布时间】:2013-12-25 23:04:41
【问题描述】:
我正在查看来自 ludumdale(minicraft) 的 Notch 的代码,我注意到他使用了:
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
所以我做了一个简单的测试程序,我注意到与我之前使用的方法相比,我的性能下降了很多。使用这种方法,只需绘制一个全白的屏幕,我就可以得到 800 fps,而当我绘制测试图像时,我会得到 1200 以上,这似乎有点奇怪。即使我没有在pixels[] 上声明任何内容,只保留默认值,它仍然是 800 fps。我想知道是否有人可以解释我这样做的原因。这是我编写的测试代码,我使用 fraps 来获取我的 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();
}
}
我只是将testImage 替换为image。谢谢大家,节日快乐
编辑:我注意到只需调用 int[] pixel = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();大大降低了应用程序的速度。有人可以解释一下为什么会这样吗?我需要处理像素还是什么?谢谢
【问题讨论】:
标签: java graphics jframe bufferedimage