异常信息:
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@a693a8f
at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1271)
at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:257)
at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
at android.widget.ImageView.onDraw(ImageView.java:1268)
at android.view.View.draw(View.java:17071)
at android.view.View.updateDisplayListIfDirty(View.java:16053)
at android.view.View.draw(View.java:16837)
at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
at android.view.View.updateDisplayListIfDirty(View.java:16048)
at android.view.View.draw(View.java:16837)
先看createScaledBitmap()源码:
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,
boolean filter) {
Matrix m = new Matrix();
final int width = src.getWidth();
final int height = src.getHeight();
if (width != dstWidth || height != dstHeight) {
final float sx = dstWidth / (float) width;
final float sy = dstHeight / (float) height;
m.setScale(sx, sy);
}
return Bitmap.createBitmap(src, 0, 0, width, height, m, filter);
}
实际是调用了 createBitmap() ,部分源码如下:
public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
@Nullable Matrix m, boolean filter) {
checkXYSign(x, y);
checkWidthHeight(width, height);
if (x + width > source.getWidth()) {
throw new IllegalArgumentException("x + width must be <= bitmap.width()");
}
if (y + height > source.getHeight()) {
throw new IllegalArgumentException("y + height must be <= bitmap.height()");
}
if (source.isRecycled()) {
throw new IllegalArgumentException("cannot use a recycled source in createBitmap");
}
// check if we can just return our argument unchanged
if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
height == source.getHeight() && (m == null || m.isIdentity())) {
return source;
}
源码重点:当以下条件成立时 ,返回原bitmap,就不再生成新的bitmap
// check if we can just return our argument unchanged
if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
height == source.getHeight() && (m == null || m.isIdentity())) {
return source;
}
导致问题出现的原因:由于createScaleBitmap 返回的是原bitmap ,且并没有重新生成新的bitmap ,而后面做了bitmap回收处理,导致异常错误
Bitmap newBp = Bitmap.createScaledBitmap(tmpBitmap, width,height, true);
tmpBitmap.recycle();
tmpBitmap=null;
imageView.setImageBitmap(newBp);
解决方案:只需要把上面的条件改为不成立即可,强制生成新bitmap ,或者也可以做width,height 判断处理
如:在生成原bitmap 时 使用
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;