編輯:進階開發
在 Android 平台上,特別是 FPS 這類遊戲,用一般方式截圖常常會失敗。由於系統底層讀取 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;
}
}
return Bitmap.createBitmap(bt, w, h, true);
}
這段程式透過 glReadPixels 讀取 RGBA 分量,並以 (h - i - 1) 做垂直翻轉,最後生成 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);
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 物件,就能把當前畫面存成圖檔。
從 Windows Mobile 開發者的視角看 Android 開發環境建置
Andrew Koenig 寫過一本現代 C++ 的經典教材《Accelerated C++》。而這麼多年過去,Android 的狀況改善了嗎?它真的還像當年大家口中那樣
Android 輸入法開發實戰:IMF 框架與 SoftKeyboard 範例全解析
從 SDK 1.5 起,Android 開放了 IMF(Input Method Framework),第三方得以打造自己的輸入法。要入門 IMF,最直接的參考莫過於官方
從零開始:Android SDK 與 Eclipse 開發環境完整建置教學
一、背景與前置準備 1. Android 是什麼 Android 是 Google 於 2007 年 11 月 5 日公布的開放原始碼手機作業系統,以 Linux 核心為
NDK 入門專案實戰(四)
這裡的程式碼會在運行時向 sdcard 寫入 androidos.cc.txt 檔案,然後寫入 aaaa 這組資料。 6. 編譯 SO 檔案 開始編譯 so。先在 NDK