public class UI {
private static final Canvas sCanvas = new Canvas();
public static Bitmap createBitmapFromView(View view) {
return createBitmapFromView(view, 1f);
}
/**
* 从一个view创建Bitmap。
* 注意点:绘制之前要清掉 View 的焦点,因为焦点可能会改变一个 View 的 UI 状态。
*
* @param view 传入一个 View,会获取这个 View 的内容创建 Bitmap。
* @param scale 缩放比例,对创建的 Bitmap 进行缩放,数值支持从 0 到 1。
*/
public static Bitmap createBitmapFromView(View view, float scale) {
if (view instanceof ImageView) {
Drawable drawable = ((ImageView) view).getDrawable();
if (drawable != null && drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
}
view.clearFocus();
Bitmap bitmap = createBitmapSafely((int) (view.getWidth() * scale),
(int) (view.getHeight() * scale), Bitmap.Config.ARGB_8888, 1);
if (bitmap != null) {
synchronized (sCanvas) {\
// 方式1
Canvas canvas = sCanvas;
canvas.setBitmap(bitmap);
canvas.save();
// 防止 View 上面有些区域空白导致最终 Bitmap 上有些区域变黑
canvas.drawColor(Color.WHITE);
canvas.scale(scale, scale);
view.draw(canvas);
canvas.restore();
canvas.setBitmap(null);
// 方式2 Android 9 以上
Rect rect = new Rect();
rect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
PixelCopy.request(((Activity)view.getContext()).getWindow(), rect, bitmap, (cs) -> {
if (cs == PixelCopy.SUCCESS) {
if (targetView instanceof ImageView) {
// 成功后的回调
}
}
}, new Handler(Looper.getMainLooper()));
}
}
return bitmap;
}
/**
* 安全的创建bitmap。
* 如果新建 Bitmap 时产生了 OOM,可以主动进行一次 GC - System.gc(),然后再次尝试创建。
*
* @param width Bitmap 宽度。
* @param height Bitmap 高度。
* @param config 传入一个 Bitmap.Config。
* @param retryCount 创建 Bitmap 时产生 OOM 后,主动重试的次数。
* @return 返回创建的 Bitmap。
*/
public static Bitmap createBitmapSafely(int width, int height, Bitmap.Config config, int retryCount) {
try {
return Bitmap.createBitmap(width, height, config);
} catch (OutOfMemoryError e) {
e.printStackTrace();
if (retryCount > 0) {
System.gc();
return createBitmapSafely(width, height, config, retryCount - 1);
}
return null;
}
}
}
创建一个缩略图Bitmap(使用PixelCopy)
最新推荐文章于 2024-05-26 09:59:01 发布