從事Android開發(fā)的道友一定碰到過這樣的需求:把UI布局轉(zhuǎn)換成圖片保存到本地或者分享出去。在查閱了大量網(wǎng)上資料后發(fā)現(xiàn),最常用的解決方案不外乎以下兩種:
1、使用View自帶的DrawingCache機(jī)制獲取Bitmap(This method was deprecated in API level 28)
//開啟DrawingCache
targetView.setDrawingCacheEnabled(true);
//構(gòu)建開啟DrawingCache
targetView.buildDrawingCache();
//獲取Bitmap
Bitmap drawingCache = targetView.getDrawingCache();
//方法回調(diào)
getCacheResult.result(drawingCache);
//銷毀DrawingCache
targetView.destroyDrawingCache();
2、使用PixelCopy提供的像素復(fù)制能力,完成從Surface到位圖的復(fù)制操作(Added in API level 24)
//準(zhǔn)備一個(gè)bitmap對象,用來接收copy出來的像素
final Bitmap bitmap = Bitmap.createBitmap(targetView.getWidth(), targetView.getHeight(), Bitmap.Config.ARGB_8888);
//獲取layout的left-top頂點(diǎn)位置
final int[] location = new int[2];
targetView.getLocationInWindow(location);
//請求轉(zhuǎn)換
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) {
//方法回調(diào)
getCacheResult.result(bitmap);
}
}
}, new Handler(Looper.getMainLooper()));
盡管以上兩種方法都可以實(shí)現(xiàn)需求,但是官方推薦使用PixelCopy API,因此我們在新設(shè)備上應(yīng)該盡量使用新API。
綜合方法:
/**
* View轉(zhuǎn)換成Bitmap
*
* @param targetView targetView
* @param getCacheResult 轉(zhuǎn)換成功回調(diào)接口
*/
public static void getBitmapFromView(@NotNull Activity activity, View targetView, final CacheResult getCacheResult) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//準(zhǔn)備一個(gè)bitmap對象,用來將copy出來的區(qū)域繪制到此對象中
final Bitmap bitmap = Bitmap.createBitmap(targetView.getWidth(), targetView.getHeight(), Bitmap.Config.ARGB_8888);
//獲取layout的left-top頂點(diǎn)位置
final int[] location = new int[2];
targetView.getLocationInWindow(location);
//請求轉(zhuǎn)換
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) {
//方法回調(diào)
getCacheResult.result(bitmap);
}
}
}, new Handler(Looper.getMainLooper()));
} else {
//開啟DrawingCache
targetView.setDrawingCacheEnabled(true);
//構(gòu)建開啟DrawingCache
targetView.buildDrawingCache();
//獲取Bitmap
Bitmap drawingCache = targetView.getDrawingCache();
//方法回調(diào)
getCacheResult.result(drawingCache);
//銷毀DrawingCache
targetView.destroyDrawingCache();
}
}