BitmapFactory.decodeResource 返回爲 null 的問題

問題代碼:canvas

Bitmap bmp = BitmapFactory.decodeResource(resources, R.drawable.ic_image);bash

其中 R.drawable.ic_image ,此代碼在 4.4 上運行正常,但在 5.0 以上的系統會出現空指針,緣由在於此原本方法不能將 vector 轉化爲 bitmap ,而apk編譯時爲了向下兼容,會根據 vector 生產相應的 png ,而 4.4 的系統運行此代碼時其實用的是 png 資源。這就是爲何 5.0 以上會報錯,而 4.4 不會的緣由。ui

解決方案:spa

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;
}
複製代碼
相關文章
相關標籤/搜索