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;
}
复制代码
相关文章
相关标签/搜索