现在我使用的是来自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);
/**/
}
}
答案 0 :(得分:2)
获得更多FPS的方法可能是使用BufferStrategy
。您不必使用Graphics
传递我的paint()
方法,而是必须使用例如jFrame.createBufferStrategy(/*number of buffers*/)
和BufferStrategy bufferStrategy = jFrame.getBufferStrategy()在外部创建它们。
如果您想要访问Graphics
,则使用Graphics g = bufferStrategy.getDrawGraphics()
,然后通常绘制您的图片。我不确定这是否会在这么简单的例子中真正改善你的FPS,但是当做更复杂的抽奖时,它肯定会。
BufferStrategy
是没用的,因为它会继续直接绘制到屏幕上。缓冲区大小应为2-5,具体取决于您的图形卡可以处理多少vram。