android webView截图的4种方法
android在webView里面截图大概有四种方式,具体内容如下
1.获取到DecorView然后将DecorView转换成bitmap然后写入到文件里面.
Viewview=getWindow().getDecorView();
Bitmapbitmap=Bitmap.createBitmap(view.getWidth(),view.getHeight(),Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(bitmap);
view.draw(canvas);
Log.d(TAG,"bitmap--"+bitmap);
try{
StringfileName=Environment.getExternalStorageDirectory().getPath()+"/webview_jietu.jpg";
FileOutputStreamfos=newFileOutputStream(fileName);
//压缩bitmap到输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG,70,fos);
fos.close();
Toast.makeText(WebviewFromGetDecorView.this,"截屏成功",Toast.LENGTH_LONG).show();
}catch(Exceptione){
Log.e(TAG,e.getMessage());
}finally{
if(bitmap!=null){
bitmap.recycle();
}
}
2.使用webViewpicture来实现该功能.(该方法被废弃了因此不建议使用)
Picturepicture=webView.capturePicture();
intwidth=picture.getWidth();
intheight=picture.getHeight();
if(width>0&&height>0){
Bitmapbitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(bitmap);
picture.draw(canvas);
try{
StringfileName=Environment.getExternalStorageDirectory().getPath()+"/webview_jietu.jpg";
FileOutputStreamfos=newFileOutputStream(fileName);
//压缩bitmap到输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG,70,fos);
fos.close();
Toast.makeText(WebviewFromCapture.this,"截屏成功",Toast.LENGTH_LONG).show();
bitmap.recycle();
}catch(Exceptione){
Log.e(TAG,e.getMessage());
}
}
3.使用webViewDraw来实现.(该方法被废弃了因此不建议使用)
floatscale=webView.getScale();
intwebViewHeight=(int)(webView.getContentHeight()*scale+0.5);
Bitmapbitmap=Bitmap.createBitmap(webView.getWidth(),webViewHeight,Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(bitmap);
webView.draw(canvas);
try{
StringfileName=Environment.getExternalStorageDirectory().getPath()+"/webview_jietu.jpg";
FileOutputStreamfos=newFileOutputStream(fileName);
//压缩bitmap到输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG,70,fos);
fos.close();
Toast.makeText(WebviewFromDraw.this,"截屏成功",Toast.LENGTH_LONG).show();
bitmap.recycle();
}catch(Exceptione){
Log.e(TAG,e.getMessage());
}
4.使用webViewDrawCache来实现(建议使用).
Bitmapbitmap=webView.getDrawingCache();
try{
StringfileName=Environment.getExternalStorageDirectory().getPath()+"/webview_jietu.jpg";
FileOutputStreamfos=newFileOutputStream(fileName);
//压缩bitmap到输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG,70,fos);
bitmap.recycle();
fos.close();
Toast.makeText(WebviewFromDrawCache.this,"截屏成功",Toast.LENGTH_LONG).show();
}catch(Exceptione){
Log.e(TAG,e.getMessage());
}finally{
bitmap.recycle();
}
注意:
在android5.0及以上版本使用webView进行截长图时,默认是截取可是区域内的内容.因此需要在支撑窗体内容之前加上如下方法.
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
WebView.enableSlowWholeDocumentDraw();
}
setContentView(R.layout.activity_webview);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。