1. 程式人生 > >BitmapFactory.decodeResource為null的處理方法之一

BitmapFactory.decodeResource為null的處理方法之一

問題程式碼:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.danger_build10);

其中R.drawable.danger_build10是一個vector圖片,此程式碼在4.4上執行正常,但在5.0以上的系統會出現空指標,原因在於此本來方法不能將vector轉化為bitmap,而apk編譯時為了向下相容,會根據vector生產相應的png,而4.4的系統執行此程式碼時其實用的是png資源。這就是為什麼5.0以上會報錯,而4.4不會的原因

下面是解決辦法

private static Bitmap getBitmap(Context context,int vectorDrawableId) {
    Bitmap bitmap=null;
if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){ Drawable vectorDrawable = context.getDrawable(vectorDrawableId); bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); vectorDrawable.draw(canvas); }else { bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId); } return bitmap; }