需求里需要进行控件的截图,webview试了多种方法不行,最后找到一种稳定的方法。
以下代码分:短截图,长截图,保存在本地如下:
webview长截图在5.0以上手机请先添加此方法:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { android.webkit.WebView.enableSlowWholeDocumentDraw(); } setContentView(R.layout.e_cc);
短截图方法:
public void getcurret() { Bitmap bitmap = Bitmap.createBitmap(mWebView.getWidth(), mWebView.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); canvas.drawBitmap(bitmap, mWebView.getWidth(), mWebView.getHeight(), new Paint()); mWebView.draw(canvas); save(bitmap, "wc.jpg"); }
长截图方法
public void getlong() { float scale = mWebView.getScale(); Log.e("scale:", scale + ""); int width = mWebView.getWidth(); int height = (int) (mWebView.getContentHeight() * scale + 0.5); Bitmap longImage = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(longImage); mWebView.draw(canvas); save(longImage, "wl.jpg"); }
ScrollView长截图方法:
public void getSV() { int h = 0; for (int i = 0; i < mScrollView.getChildCount(); i++) { View view = mScrollView.getChildAt(i); h = view.getHeight() + h; } Bitmap bitmap = Bitmap.createBitmap(mScrollView.getWidth(), h, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); mScrollView.draw(canvas); save(bitmap, "s.jpg"); }
保存在本地方法:
public void save(Bitmap bitmap, String s2) { String s1 = Environment.getExternalStorageDirectory().getAbsolutePath(); File file = new File(s1, "wt"); if (!file.exists()) { file.mkdirs(); } FileOutputStream out = null; File file1 = new File(file, s2); try { out = new FileOutputStream(file1); } catch (FileNotFoundException e) { e.printStackTrace(); } try { if (null != out) { bitmap.compress(Bitmap.CompressFormat.JPEG, 20, out); out.flush(); out.close(); Log.e("save:", "完成"); } } catch (IOException e) { e.printStackTrace(); } }
网上有一种长截图方法,测试后不能用,知道原因请回复探讨:
mWebView.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); mWebView.layout(0, 0, mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight()); mWebView.setDrawingCacheEnabled(true); mWebView.buildDrawingCache(); Bitmap longImage = Bitmap.createBitmap(mWebView.getMeasuredWidth(), mWebView.getMeasuredHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(longImage); // 画布的宽高和 WebView 的网页保持一致 Paint paint = new Paint(); canvas.drawBitmap(longImage, 0, mWebView.getMeasuredHeight(), paint); mWebView.draw(canvas);