怎样获取当前屏并保存成为图片?
思路有两个:
1 可以利用android为了提高滚动等各方面的绘制速度,为每一个view创建了一个缓存,使用 View.buildDrawingCache方法可以获取相应view的cache,这个cache就是一个bitmap对象。
2 通过查看View的源码发现有一个方法createSnapshot,但是它是@hide隐藏的,但是我们可以通过反射的 方法调用可以拿到Bitmap。
下面就两个思路分别写两个方法获取当前屏幕的Bitmap:
/**
* 可以利用android为了提高滚动等各方面的绘制速度,为每一个view创建了一个缓存,使用 View.buildDrawingCache方法可以获取相应view的cache,这个cache就是一个bitmap对象
* @return Bitmap
*/
private BitmapscreenShotWholeScreen() {
View dView = getWindow().getDecorView().getRootView();//拿到当前屏幕的rootview
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bitmap = dView.getDrawingCache();
return bitmap;
}
/**
* 通过查看View的源码发现有一个方法createSnapshot,但是它是@hide隐藏的,但是我们可以通过反射方法调用可以拿到Bitmap。
* @return Bitmap
*/
private BitmapgetScreenBitMap() {
View rootView = getWindow().getDecorView().getRootView();//拿到当前屏幕的rootview
Bitmap bitmap=null;
try {
final Method createSnapshot = View.class.getDeclaredMethod("createSnapshot", Bitmap.Config.class, Integer.TYPE, Boolean.TYPE);
createSnapshot.setAccessible(true);
bitmap = (Bitmap) createSnapshot.invoke(rootView, Bitmap.Config.RGB_565, Color.WHITE, false);
}catch (final NoSuchMethodException e) {
Log.e(TAG, "Can't call createSnapshot, will use drawCache", e);
}catch (final IllegalArgumentException e) {
Log.e(TAG, "Can't call createSnapshot with arguments", e);
}catch (final InvocationTargetException e) {
Log.e(TAG, "Exception when calling createSnapshot", e);
}catch (final IllegalAccessException e) {
Log.e(TAG, "Can't access createSnapshot, using drawCache", e);
}catch (final ClassCastException e) {
Log.e(TAG, "createSnapshot didn't return a bitmap?", e);
}
return bitmap;
}
有可能在getDrawingCache()可能为null的情况,那么可以rootView重新测量,布局
rootView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
rootView.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
以上是两种截当前屏幕的方式,后续看截长屏...
网友评论