实现
1.单个view的截图
2.webview的截长图
3.scrollView的截图
4.截屏
1.单个View的截图
View.getDrawingCache
通过view的cache来获取view的截图
view.setDrawingCacheEnabled(true);//开启view缓存
view.buildDrawingCache();//通知view生产绘图缓存
Bitmap bitmap = view.getDrawingCache();//获取view的截图
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();//销毁缓存
2.webview的截图
mWebView.capturePicture()
重点是webView的capturePicture()方法
Picture snapShot = mWebView.capturePicture();//传入webview对象
final Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(),snapShot.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
snapShot.draw(canvas);
3.scrollView的截图
scrollView的截图比较特殊,因为他存在长图;
如果我们仍然使用第一种方法来获取截图,我们会碰到 超出缓存的警告 (View too large to fit into drawing cache)
在这时候,scrollview的getheight()高度是子view的实际高度,而子view还没完全显示,他的高度是大于屏幕高度的,所以会提示超出缓存。
public static Bitmap shotScrolleView(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY));
view.layout((int) view.getX(), (int) view.getY(), (int) view.getX() + view.getMeasuredWidth(), (int) view.getY() + view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
4.截屏
截屏原理和方法一类似,重点是获取到decorView,然后使用和方法一样
public void screenShot(Activity activity) {
View dView = activity.getWindow().getDecorView();//重点
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
saveToLocal(bitmap,"screenshot.jpeg");
}
网友评论