从 Drawable Resource Id 解码位图给出 null

Decoding bitmap from Drawable Resource Id is giving null

我想从可绘制资源 ID 获取位图,我找到了使用 BitmapFactory 解码方法对其进行解码的解决方案,但它给出的是 null。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_tick);

请检查您使用的是 Vector drawable 还是普通 png/jpeg 图像作为 drawable,如果您尝试解码 vector drawable,它会给出 null 值。

如果您尝试解码 Vector drawable,请使用此代码

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    drawable = (DrawableCompat.wrap(drawable)).mutate();
}

Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
        drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

return bitmap;
}

还要确保您的应用程序中是否启用了矢量支持gradle

vectorDrawables.useSupportLibrary = true