2015-11-01 36 views
2

現在我使用Dummy’s guide to drawing raw images in Java 2D 的採用代碼我在Debian i386上使用Oracle JVM,Nvidia 8600 GTS和Intel Core 2Duo 2.6 GHz獲得240 FPS,800x600窗口。什麼是在Java中繪製像素緩衝區的最快方式

是否存在更快的方式?我的代碼:

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); 
     /**/ 
    } 
} 

snapshot

+2

這裏的問題是什麼? *是否存在更快的方式?* - 是否240 fps不夠快?截圖與你的問題有什麼關係?它看起來像一些錯誤的... –

+2

沒有錯,它是屏幕充滿增量int_argb,爲測試。 – biv

+0

在此處查看相關的[示例](https://sites.google.com/site/drjohnbmatthews/raster)。 – trashgod

回答

2

一種方式來獲得更多的FPS很可能是使用BufferStrategy。而不是使用Graphics通過我的paint()方法,您將不得不使用例如外部創建它們。 jFrame.createBufferStrategy(/*number of buffers*/)和BufferStrategy bufferStrategy = jFrame.getBufferStrategy()。 如果您然後想要訪問Graphics,則使用Graphics g = bufferStrategy.getDrawGraphics(),然後照常繪製圖像。我不確定這樣一個簡單的例子是否能夠真正改善您的FPS,但是當進行更復雜的繪製時,它肯定會。

編輯:創建BufferStrategy只有1個backbuffer是很沒用的,因爲它只會繼續直接畫到屏幕上。 buffersize應該是2-5,具體取決於您的圖形卡可以處理多少vram。

+1

謝謝,FPS增加了10 :) – biv

相關問題