一個將當前屏幕保存爲圖片文件的類(簡單說就是抓屏)

如今不管是應用,仍是遊戲中,都常常會有分享的功能。分享,不只要分享文字,也要分享應用或者遊戲的屏幕截圖,這樣才能作到圖文並茂,吸引到更多的用戶。java

想要作圖片的分享功能,首先就須要抓屏,將當前屏幕保存爲一個圖片文件。android

下面就是一個將當前的Activity直接保存爲一個圖片文件的類庫,能夠直接使用。須要的,直接拿來主義就行了。app


  1. package com.gaolei.framework.android.util;  ui

  2.   

  3. import java.io.File;  spa

  4. import java.io.FileNotFoundException;  orm

  5. import java.io.FileOutputStream;  遊戲

  6. import java.io.IOException;  圖片

  7.   

  8. import android.app.Activity;  get

  9. import android.graphics.Bitmap;  it

  10. import android.graphics.Rect;  

  11. import android.view.View;  

  12.   

  13. public class ScreenShot {  

  14.   

  15.     private static Bitmap takeScreenShot(Activity activity) {  

  16.         // View是你須要截圖的View  

  17.         View view = activity.getWindow().getDecorView();  

  18.         view.setDrawingCacheEnabled(true);  

  19.         view.buildDrawingCache();  

  20.         Bitmap b1 = view.getDrawingCache();  

  21.   

  22.         // 獲取狀態欄高度  

  23.         Rect frame = new Rect();  

  24.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  

  25.         int statusBarHeight = frame.top;  

  26.   

  27.         // 獲取屏幕長和高  

  28.         int width = activity.getWindowManager().getDefaultDisplay().getWidth();  

  29.         int height = activity.getWindowManager().getDefaultDisplay()  

  30.                 .getHeight();  

  31.         // 去掉標題欄  

  32.         Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height  

  33.                 - statusBarHeight);  

  34.         view.destroyDrawingCache();  

  35.         return b;  

  36.     }  

  37.   

  38.     private static void savePic(Bitmap b, File filePath) {  

  39.         FileOutputStream fos = null;  

  40.         try {  

  41.             fos = new FileOutputStream(filePath);  

  42.             if (null != fos) {  

  43.                 b.compress(Bitmap.CompressFormat.PNG, 100, fos);  

  44.                 fos.flush();  

  45.                 fos.close();  

  46.             }  

  47.         } catch (FileNotFoundException e) {  

  48.             // e.printStackTrace();  

  49.         } catch (IOException e) {  

  50.             // e.printStackTrace();  

  51.         }  

  52.     }  

  53.   

  54.     public static void shoot(Activity a, File filePath) {  

  55.         if (filePath == null) {  

  56.             return;  

  57.         }  

  58.         if (!filePath.getParentFile().exists()) {  

  59.             filePath.getParentFile().mkdirs();  

  60.         }  

  61.         ScreenShot.savePic(ScreenShot.takeScreenShot(a), filePath);  

  62.     }  

  63. }  

相關文章
相關標籤/搜索