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

Android 在 OpenGL 環境下如何實作截圖

編輯:進階開發

在 Android 平台上,特別是 FPS 這類遊戲,用一般方式截圖常常會失敗。由於系統底層讀取 framebuffer 的效率不高,截出來的畫面可能因為刷新問題,出現上半部與下半部不匹配的狀況。本文提供一個在 GL 環境中直接讀取像素的正確做法。

讀取像素並轉為 Bitmap

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;
}
}
return Bitmap.createBitmap(bt, w, h, true);
}

這段程式透過 glReadPixels 讀取 RGBA 分量,並以 (h - i - 1) 做垂直翻轉,最後生成 Android 通用的 Bitmap 物件。

儲存為 PNG

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);
bmp.compress(CompressFormat.PNG, 100, fos); // 存為 PNG,品質 100%
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

提醒:Android 2.2 以上版本,sdcard 路徑為 /mnt/sdcard/。呼叫時直接執行這個靜態方法即可,例如:

SavePNG(0, 0, Config.SCREEN_W, Config.SCREEN_H, "cwj.png", gl);

最後一個參數傳入你的 OpenGL 物件,就能把當前畫面存成圖檔。

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