根据先前的答案,可以简化为既匹配VectorDrawable也可以匹配BitmapDrawable,并且至少与API 15兼容。
public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) {
Drawable drawable = AppCompatResources.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof VectorDrawableCompat || drawable instanceof VectorDrawable) {
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;
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
然后,您必须添加gradle文件:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
在棒棒糖之前,它将使用VectorDrawableCompat;在棒棒糖上,它将使用VectorDrawable。
编辑
我已经根据@ user3109468的评论编辑了条件