现在我正在使用Dummy’s guide to drawing raw images in Java 2D中采用的代码
在配备Oracle JVM,Nvidia 8600 GTS和Intel Core 2Duo 2.6 GHz的Debian i386上,我获得了240 FPS,适用于800x600窗口。
存在更快的方法吗?我的代码:
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class TestFillRasterRate
{
static class MyFrame extends JFrame
{
long framesDrawed;
int col=0;
int w, h;
int[] raster;
ColorModel cm;
DataBuffer buffer;
SampleModel sm;
WritableRaster wrRaster;
BufferedImage backBuffer;
//@Override public void paint(Graphics g)
public void draw(Graphics g)
{
// reinitialize all if resized
if( w!=getWidth() || h!=getHeight() )
{
w = getWidth();
h = getHeight();
raster = new int[w*h];
cm = new DirectColorModel(24, 255, 255<<8, 255<<16);
buffer = new DataBufferInt(raster, raster.length);
sm = cm.createCompatibleSampleModel(w,h);
wrRaster = Raster.createWritableRaster(sm, buffer, null);
backBuffer = new BufferedImage(cm, wrRaster, false, null);
}
// produce raster
for(int ptr=0, x=0; x<w; x++)
for(int y=0; y<h; y++)
raster[ptr++] = col++;
// draw raster
g.drawImage(backBuffer, 0,0, null);
++framesDrawed;
/**
SwingUtilities.invokeLater(new Runnable()
{ @Override public void run()
{ repaint();
}
});/**/
}
}
public static void main(String[] args)
{
final MyFrame frame = new MyFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// draw FPS in title
new Timer(1000, new ActionListener()
{ @Override public void actionPerformed(ActionEvent e)
{ frame.setTitle(Long.toString(frame.framesDrawed));
frame.framesDrawed = 0;
}
}).start();
/**/
frame.createBufferStrategy(1);
BufferStrategy bs = frame.getBufferStrategy();
Graphics g = bs.getDrawGraphics();
for(;;)
frame.draw(g);
/**/
}
}
最佳答案
获取更多FPS的方法可能是使用BufferStrategy
。而不是使用通过Graphics
方法传递的paint()
,您必须在外部使用例如jFrame.createBufferStrategy(/*number of buffers*/)
和BufferStrategy bufferStrategy = jFrame.getBufferStrategy()创建它们。
如果随后要访问Graphics
,请使用Graphics g = bufferStrategy.getDrawGraphics()
,然后照常绘制图像。我不确定是否可以通过这样一个简单的示例真正改善FPS,但是当进行更复杂的绘制时,肯定会。
编辑:创建仅具有1个后缓冲的BufferStrategy
几乎没有用,因为它将直接继续直接绘制到屏幕上。缓冲区大小应为2-5,具体取决于您的图形卡可以处理多少个vram。