公司之前老項目升級:之前使用:BitmapFactory.decodeFile(path,myOptions);一直很好的,今天突然 ‘int android.graphics.Bitmap.getWidth()’ on a null 一直報null。
奇怪的是,28一下手機正常,29不正常。馬上想到是Android Q的特性。
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inJustDecodeBounds=true;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
this.mBitmap=BitmapFactory.decodeFile(path,myOptions);
在此之前,還搜索看了不少,不是說讀寫權限沒給,就是圖片太大,其實壓根都不是。
解決代碼如下:
//java
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.P){
this.mBitmap=BitmapFactory.decodeFile(path,picOptions);
}else{
ContentResolver contentResolver=getContext().getContentResolver();
ParcelFileDescriptor fd = null;
try {
fd = contentResolver.openFileDescriptor(Uri.parse(path), "r");
if (fd != null) {
this.mBitmap = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
fd.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
kotlin:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
this.mBitmap = BitmapFactory.decodeFile(path, picOptions)
} else {
val contentResolver: ContentResolver = getContext().getContentResolver()
var fd: ParcelFileDescriptor? = null
try {
fd = contentResolver.openFileDescriptor(Uri.parse(path), "r")
if (fd != null) {
this.mBitmap = BitmapFactory.decodeFileDescriptor(fd.fileDescriptor)
fd.close()
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
另外在Android Q上drawbitmap要使用先繪製矩形, canvas.drawBitmap(bitmap,null,rect,null);的方案。若直接使用這個API:圖片會變形。
public void drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint)