1. 程式人生 > >Android獲取webView快照與螢幕截圖的方法

Android獲取webView快照與螢幕截圖的方法

        前段時間做的一個書店專案其閱讀模組中用到了WebView + js,今天把WebView這塊用到的幾個特性記錄下。

其主要用到了webView的快照與螢幕的截圖。部分程式碼如下:

    /**
     * 擷取webView可視區域的截圖
     * @param webView 前提:WebView要設定webView.setDrawingCacheEnabled(true);
     * @return
     */
	private Bitmap captureWebViewVisibleSize(WebView webView){
		Bitmap bmp = webView.getDrawingCache();
		return bmp;
	}


 這個方法只擷取螢幕中顯示出來部分的webView畫面,未顯示的部分不會被擷取。

	/**
	 * 擷取webView快照(webView載入的整個內容的大小)
	 * @param webView
	 * @return
	 */
	private Bitmap captureWebView(WebView webView){
		Picture snapShot = webView.capturePicture();
		
		Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(),snapShot.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);
		snapShot.draw(canvas);
		return bmp;
	}


這個看好與上一個是不同的,他是擷取webView的整個頁面,未顯示的也會被擷取。

	/**
	 * 截圖
	 * @param context
	 * @return
	 */
    private Bitmap captureScreen(Activity context){
      View cv = context.getWindow().getDecorView();
      Bitmap bmp = Bitmap.createBitmap(cv.getWidth(), cv.getHeight(),Config.ARGB_8888);
      Canvas canvas = new Canvas(bmp);
      cv.draw(canvas);
      return bmp;
    }


這個不用多說大家都明白就是手機螢幕的快照~~

核心方法就這些了。知道大家都喜歡要專案原始碼,最好是下載下來能匯入eclipse執行的(我是好喜歡這樣滴博文)~~

我這寫好的Demo是把擷取的快照儲存到SD卡中,需要的猛擊這裡哈~~~