一、調用api接口view.getDrawingCache()獲取抓取當前屏幕的截圖
調用接口view.getDrawingCache()獲取當前繪制緩存中的位圖
package com.screenshoot; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Rect; import android.util.Log; import android.view.View; public class ScreenShot { // 獲取指定Activity的截屏,保存到png文件 private static Bitmap takeScreenShot(Activity activity) { // View是你需要截圖的View View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); // 獲取狀態欄高度 Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; Log.i("TAG", "" + statusBarHeight); // 獲取屏幕長和高 int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay() .getHeight(); // 去掉標題欄 // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455); Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; } // 保存到sdcard private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 程序入口 public static void shoot(Activity a,String b) { //ScreenShot.savePic(ScreenShot.takeScreenShot(a), "sdcard/xx.png"); ScreenShot.savePic(ScreenShot.takeScreenShot(a), b); } }
方案缺點:
1、只能抓取靜態view。對於正在播放視頻(采用surfaceview)或者動態壁紙等等,抓屏結果為黑屏。這是因為surfaceview不同於view,底層實現是不一樣的。SurfaceView和View最本質的區別在於,surfaceView是在一個新起的單獨線程中可以重新繪制畫面而View必須在UI的主線程中更新畫面
2、從點擊按鍵開始抓屏到形成正確的png圖片,需要一段時間(不同STB性能,不同線程數量,不同時間間隔),不能夠達到實時輸出png圖片的目的
二、直接讀取/dev/graphics/fb0,並轉換成png格式圖片
/dev/graphics/fb0是Android平台下的framebuffer設備。對此方法,網絡上有很多的相關文檔(大部分都是提問):
http://wiseideal.iteye.com/blog/1250175
#adb pull /dev/graphics/fb0 fb0 #ffmpeg -vframes 1 -vcodec rawvideo -f rawvideo -pix_fmt rgb32 -s 1280x720 -i fb0 -f image2 -vcodec png image.png
上面兩行只是使用adb.exe以及ffmpeg.exe將fb0(rgb16文件)輸出為image.png文件。至於在代碼中加入轉換格式以及保存文件,可參考上面的鏈接(Runtime.getRuntime().exec("cat /dev/graphics/fb0"),以及調用busybox相關命令),這些代碼有待研究。
對於目前的不同STB,使用上述兩行命令后,得出的image.png文件為花屏(頁面看不清楚,如同DDMS上抓屏工具得出的圖片一樣),懷疑是否平台對framebuffer等做過處理。
方案缺點:
1、需要root權限---移植性不高
2、如果需要調用Runtime.getRuntime().exec等相關命令,有可能造成STB死機
3、對於某些盒子,因為硬件或者底層的限制,不能正確得到相關圖片(使用Android自帶的截屏工具DDMS中Screen Capture都不可以)
三、surfaceview -> canvas-〉bitmap
http://topic.csdn.net/u/20110519/13/37eada57-1645-42da-a195-ccc4108d3282.html
需要深入研究