Android WebView实现长截图

Android网页长截图功能实现

在安卓开发过程中,有时候会需要进行长截图,而传统截图都是单张截图,若我们想获取整个网页的内容做长截图该怎么做呢?

1.首先我们可以先处理一下链接

// 打开网页
String content = mContentEdit.getText().toString();
if (TextUtils.isEmpty(content)) {
     
	ToastUtils.showShortToast("请输入或粘贴网址");
	return;
}
if (!content.contains("http://") && !content.contains("https://")) {
     
	content ="http://" + content;
}
if (content.contains(" ")) {
     
	// 淘宝链接转正确网址
    String host ="http://";
    if (content.contains("https://")) {
     
		host ="https://";
    }
	String s = content.substring(content.indexOf(host));
    if (s.contains(" ")) {
     
		s = s.substring(0, s.indexOf(" "));
        content = s;
    }
}
// 校验网址是否有效
if (!Patterns.WEB_URL.matcher(content).matches()) {
     
	ToastUtils.showShortToast("请输入或粘贴有效网址");
	return;
}
Intent intent =new Intent(this, WebScreenShotActivity.class);
intent.putExtra("url", content);
startActivity(intent);

2.WebView页面展示网页

 WebSettings webSettings = mWebView.getSettings();
 webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
 webSettings.setDefaultTextEncodingName("UTF-8");
 webSettings.setJavaScriptEnabled(true);
 webSettings.setUserAgentString(webSettings.getUserAgentString());
 webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
 webSettings.setSupportZoom(true);
 webSettings.setUseWideViewPort(true);
 webSettings.setBuiltInZoomControls(true);
 webSettings.setLoadWithOverviewMode(true);
 webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
 webSettings.setLoadsImagesAutomatically(true);
 webSettings.setDomStorageEnabled(true);
 webSettings.setDatabaseEnabled(true);
 webSettings.setAppCacheEnabled(true);
 mWebView.setWebViewClient(new WebViewClient() {
     
 	@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
     
    	return false;
    }
    
    @Override
    public void onPageFinished(WebView view, String url) {
     
        super.onPageFinished(view, url);
        if(!mWebView.getSettings().getLoadsImagesAutomatically()) {
     
        	mWebView.getSettings().setLoadsImagesAutomatically(true);
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
     
    	super.onPageStarted(view, url, favicon);
    });
mWebView.loadUrl(getIntent().getStringExtra("url"));

3.实现长截图功能

注意:该方法在Android4.4以下可以截取整个WebView的内容,但是在4.4以上,需要在WebView未加载之前,也就是setContentView之前,增加以下代码,才能截取整个WebView的内容。

if (Build.VERSION.SDK_INT > 19) {
     
	mWebView.enableSlowWholeDocumentDraw();
}

下面就是长截图功能实现部分:

Picture snapShot = mWebView.capturePicture();
if (snapShot == null || snapShot.getHeight() <= 0 || snapShot.getWidth() <= 0) return;
Bitmap bitmap = Bitmap.createBitmap(snapShot.getWidth(), 
						snapShot.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
snapShot.draw(canvas);

4.保存到本地相册,并刷新

try {
     
    String fileName = Environment.getExternalStorageDirectory().getPath()+"/temp_capture.jpg";
    FileOutputStream fos = new FileOutputStream(fileName);
    //压缩bitmap到输出流中
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
    fos.close();
    Toast.makeText(WebviewFromGetDecorView.this, "截屏成功", Toast.LENGTH_LONG).show();
    File file = new File(fileName);
    insertToSystem(mActivity, file, fileName);
} catch (Exception e) {
     
    Log.e(TAG, e.getMessage());
} finally {
     
    if(bitmap != null) {
     
    	bitmap.recycle();
    }
}

刷新媒体库方法

public void insertToSystem(Context context, File file, String fileName) {
     
	try {
     
    	MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
     
    	e.printStackTrace();
    }
    // 通知图库更新
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      // 判断SDK版本是不是4.4或者高于4.4
    	String[] paths = new String[]{
     file.getAbsolutePath()};
        MediaScannerConnection.scanFile(context, paths, null, null);
    } else {
     
        final Intent intent;
        if (file.isDirectory()) {
     
        	intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
            intent.setClassName("com.android.providers.media",
                        "com.android.providers.media.MediaScannerReceiver");
            intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
        } else {
     
            intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(file));
        }
        context.sendBroadcast(intent);
   }
}

你可能感兴趣的:(长截图,安卓,移动开发,android,webview)