Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 中階開發

Android OpenGL 環境下的截圖程式碼

編輯:中階開發

在 Android 平台上,該如何在 OpenGL 環境下截圖呢?如果是一款 FPS 類型的遊戲,用常規方式截圖時,由於 Android 系統底層讀取 framebuffer 的效率不高,截出來的画面往往會因刷新問題而產生上下兩半部不匹配的情況。在 GL 中,我們可以用下面這段程式碼來解決。

     public static Bitmap SavePixels(int x, int y, int w, int h, GL10 gl)
    {
         int b[]=new int[w*h];
         int bt[]=new int[w*h];
         IntBuffer ib=IntBuffer.wrap(b);
         ib.position(0);
         gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);
         for(int i=0; i<h; i++)
         { 
              for(int j=0; j<w; j++)
              {
                   int pix=b[i*w+j];
                   int pb=(pix>>16)&0xff;
                   int pr=(pix<<16)&0x00ff0000;
                   int pix1=(pix&0xff00ff00) | pr | pb;
                   bt[(h-i-1)*w+j]=pix1;
              }
         }                 
         Bitmap sb=Bitmap.createBitmap(bt, w, h, true);
         return sb;
    }

上面是一個簡單的 GL 讀取 RGBA 分量的方法,然後產生 Android 通用的 Bitmap 物件:

    public static void SavePNG(int x, int y, int w, int h, String fileName, GL10 gl)
    {
                Bitmap bmp=SavePixels(x,y,w,h,gl);
                try
                {
                        FileOutputStream fos=new FileOutputStream("/sdcard/android123/"+fileName); //Android123 提示,若是 2.2 或更高系統,sdcard 路徑為 /mnt/sdcard/
                        bmp.compress(CompressFormat.PNG, 100, fos); //保存為 png 格式,質量 100%
                        try
                        {
                                 fos.flush();
                        }
                        catch (IOException e)
                        {
                                 e.printStackTrace();
                        }
                        try
                        {
                                 fos.close();
                        }
                        catch (IOException e)
                        {
                                 e.printStackTrace();
                        }
                
                }
                catch (FileNotFoundException e)
                        {
                                 e.printStackTrace();
                        }
               }
}

如何呼叫呢?直接執行這個靜態方法 SavePNG 即可,例如 SavePNG(0, 0, Config.SCREEN_W, Config.SCREEN_H, "cwj.png", gl);,最後一個參數就是你的 OpenGL 物件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved