Android 将布局转换成图片(View -> Bitmap)
2019-11-19 本文已影响0人
怡红快绿
从事Android开发的道友一定碰到过这样的需求:把UI布局转换成图片保存到本地或者分享出去。在查阅了大量网上资料后发现,最常用的解决方案不外乎以下两种:
1、使用View自带的DrawingCache机制获取Bitmap(This method was deprecated in API level 28)
//开启DrawingCache
targetView.setDrawingCacheEnabled(true);
//构建开启DrawingCache
targetView.buildDrawingCache();
//获取Bitmap
Bitmap drawingCache = targetView.getDrawingCache();
//方法回调
getCacheResult.result(drawingCache);
//销毁DrawingCache
targetView.destroyDrawingCache();
2、使用PixelCopy提供的像素复制能力,完成从Surface到位图的复制操作(Added in API level 24)
//准备一个bitmap对象,用来接收copy出来的像素
final Bitmap bitmap = Bitmap.createBitmap(targetView.getWidth(), targetView.getHeight(), Bitmap.Config.ARGB_8888);
//获取layout的left-top顶点位置
final int[] location = new int[2];
targetView.getLocationInWindow(location);
//请求转换
PixelCopy.request(activity.getWindow(),
new Rect(location[0], location[1], location[0] + targetView.getWidth(), location[1] + targetView.getHeight()),
bitmap, new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
//如果成功
if (copyResult == PixelCopy.SUCCESS) {
//方法回调
getCacheResult.result(bitmap);
}
}
}, new Handler(Looper.getMainLooper()));
尽管以上两种方法都可以实现需求,但是官方推荐使用PixelCopy API,因此我们在新设备上应该尽量使用新API。
综合方法:
/**
* View转换成Bitmap
*
* @param targetView targetView
* @param getCacheResult 转换成功回调接口
*/
public static void getBitmapFromView(@NotNull Activity activity, View targetView, final CacheResult getCacheResult) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//准备一个bitmap对象,用来将copy出来的区域绘制到此对象中
final Bitmap bitmap = Bitmap.createBitmap(targetView.getWidth(), targetView.getHeight(), Bitmap.Config.ARGB_8888);
//获取layout的left-top顶点位置
final int[] location = new int[2];
targetView.getLocationInWindow(location);
//请求转换
PixelCopy.request(activity.getWindow(),
new Rect(location[0], location[1],
location[0] + targetView.getWidth(), location[1] + targetView.getHeight()),
bitmap, new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
//如果成功
if (copyResult == PixelCopy.SUCCESS) {
//方法回调
getCacheResult.result(bitmap);
}
}
}, new Handler(Looper.getMainLooper()));
} else {
//开启DrawingCache
targetView.setDrawingCacheEnabled(true);
//构建开启DrawingCache
targetView.buildDrawingCache();
//获取Bitmap
Bitmap drawingCache = targetView.getDrawingCache();
//方法回调
getCacheResult.result(drawingCache);
//销毁DrawingCache
targetView.destroyDrawingCache();
}
}