Android编程之截屏实现方法(包括scrollview与listview)

2019-12-10 19:52:57王冬梅

易采站长站为您分析Android编程之截屏实现方法,包括截取scrollview与listview屏幕的相关技巧,以及截屏图片的生成与保存技巧,需要的朋友可以参考下

本文实例讲述了Android编程之截屏实现方法。,具体如下:

 

 
  1. public class ScreenShot {  // 获取指定Activity的截屏,保存到png文件 
  2. public static Bitmap takeScreenShot(Activity activity) {  // View是你需要截图的View 
  3. View view = activity.getWindow().getDecorView();  view.setDrawingCacheEnabled(true); 
  4. view.buildDrawingCache();  Bitmap b1 = view.getDrawingCache(); 
  5. // 获取状态栏高度  Rect frame = new Rect(); 
  6. activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  int statusBarHeight = frame.top; 
  7. System.out.println(statusBarHeight);  // 获取屏幕长和高 
  8. int width = activity.getWindowManager().getDefaultDisplay().getWidth();  int height = activity.getWindowManager().getDefaultDisplay() 
  9. .getHeight();  // 去掉标题栏 
  10. // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);  Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height 
  11. - statusBarHeight);  view.destroyDrawingCache(); 
  12. savePic(b, "/sdcard/screen_test.png");  return b; 
  13. }  // 保存到sdcard 
  14. public static void savePic(Bitmap b, String strFileName) {  FileOutputStream fos = null; 
  15. try {  fos = new FileOutputStream(strFileName); 
  16. if (null != fos) {  b.compress(Bitmap.CompressFormat.PNG, 90, fos); 
  17. fos.flush();  fos.close(); 
  18. }  } catch (FileNotFoundException e) { 
  19. e.printStackTrace();  } catch (IOException e) { 
  20. e.printStackTrace();  } 
  21. }  /** 
  22. * 把View对象转换成bitmap  * */ 
  23. public static Bitmap convertViewToBitmap(View view) {  view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),