1. 程式人生 > >【Android】WebView核心與XWalk核心獲取螢幕內容截圖總結

【Android】WebView核心與XWalk核心獲取螢幕內容截圖總結

1.專案中使用到的截圖方法:

public static Bitmap getWebViewContentShot(final View view) {
if (view == null)
return null;
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(measureSpec, measureSpec);
if (view.getMeasuredWidth() <= 0 || view.getMeasuredHeight() <= 0) {
return null;
}
Bitmap bitmap;
try {
//bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.RGB_565);
bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError e) {
System.gc();
try {
//bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.RGB_565);
bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError outOfMemoryError) {
return null;
}
}
Canvas bigCanvas = new Canvas(bitmap);
Paint paint = new Paint();
int height = bitmap.getHeight();
bigCanvas.drawBitmap(bitmap, 0, height, paint);
view.draw(bigCanvas);
return bitmap;
}

2.專案中使用新核心與原版核心的獲取方法:

View webView = mWebComponent.getWebView();

if(webView instanceof WebView){

Bitmap webViewContentShot = ViewScreenShotUtil.getWebViewContentShot(webView);

Cargo cargo = Cargo.obtain();

cargo.put(MainCargoId.WebView_BITMAP_TYPE, webViewContentShot);

mObserver.handleMessage(MainMessageId.Middle_Paperang_Print_Type,cargo,null);

cargo.release();

}else{

XWalkView xWalkCommonWebView=(XWalkView) webView;

xWalkCommonWebView.captureBitmapAsync(new XWalkGetBitmapCallback() {

@Override

public void onFinishGetBitmap(Bitmap bitmap, int i) {

Cargo cargo = Cargo.obtain();

cargo.put(MainCargoId.WebView_BITMAP_TYPE, bitmap);

mObserver.handleMessage(MainMessageId.Middle_Paperang_Print_Type,cargo,null);

cargo.release();

}

});

}

最後:使用到系統核心,在onCreate()方法之前呼叫

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

android.webkit.WebView.enableSlowWholeDocumentDraw();

}