方法1
1.1 截取Activity
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
if (view == null) {
return null;
}
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
if (b1 == null) {
return null;
}
// 获取状态栏高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 获取屏幕长和高
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, b1.getHeight() - statusBarHeight);
view.destroyDrawingCache();
b1.recycle();
return b;
}
1.3 截取ViewGroup
public static Bitmap takeScreenShotView(LinnerLayout viewGroup) {
Bitmap bitmap = null;
if (viewGroup != null) {
int h = 0;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
h += viewGroup.getChildAt(i).getHeight();
}
if (viewGroup.getHeight() > h) {
h = viewGroup.getHeight();
}
bitmap = Bitmap.createBitmap(viewGroup.getWidth(), h, Config.ARGB_8888);
final Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
viewGroup.draw(c);
}
return bitmap;
}
方法2
自己生成bitmap绘制,这个地方由于自己绘制的比较麻烦,一般就是在一张图片上绘制一些文字即可
方法3
生成未加载的布局文件的分享图片
View targetView = LayoutInflater.from(mActivity).inflate(R.layout.view_share, null);
targetView.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
targetView.layout(0, 0, width, height);
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
view.draw(canvas);
核心是布局文件没有加载,也即没有measure和layout 就无法进行绘制(实际上一个view之所以能被绘制上去就是因为父容器measure和layout了它)才能进行绘制
一个知识点: view 不是不可以在后台线程修改的,而是需只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)
扩展思维
如何生成listview和recycleView的截屏
方案1
原理:我们可以知道第一个和最后一个view在屏幕上的位置,也可以获取获取整个屏幕的截图,所谓我们可以滑动一屏截取一屏(我们可以估算出一屏大约有多少元素,滚动固定长度即可)的内容,然后最后拼接出来
方案2
原理:可以逐个生成itemView的bitmap(采用方法3),然后拼接出来