BitmapFactory.decodeResource 返回为 null 的问题

3,986 阅读1分钟

问题代码:

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

其中 R.drawable.ic_image ,此代码在 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;
}