public Bitmap rotateBitmap(int degree, Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return bm; // 呼叫端若不及時 recycle 會導致 OOM
}
在 return bm; 前呼叫 bm.recycle() 會導致回傳的 Bitmap 已被回收,ImageView 顯示黑色或崩潰。
// 呼叫端
Bitmap oldBitmap = imageView.getDrawable() instanceof BitmapDrawable ?
((BitmapDrawable)imageView.getDrawable()).getBitmap() : null;
Bitmap newBitmap = rotateBitmap(90, oldBitmap);
imageView.setImageBitmap(newBitmap);
if (oldBitmap != null && oldBitmap != newBitmap && !oldBitmap.isRecycled()) {
oldBitmap.recycle();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
options.inBitmap = oldBitmap; // 重用舊記憶體塊
Bitmap newBitmap = Bitmap.createBitmap(...); // 需相容尺寸/配置
public void rotateAndDraw(Canvas canvas, Bitmap bitmap, int degree) {
canvas.save();
canvas.rotate(degree, bitmap.getWidth()/2, bitmap.getHeight()/2);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.restore();
}
LruCache 快取常用 Bitmap,減少重複解碼。inSampleSize 縮放至螢幕尺寸。recycle() 只是提示 GC,不再立即釋放。