最近在使用bitmap时发现,如果加载svg的图片转换bitmap会报异常,因为svg矢量图没办法直接转换成bitmap,需要使用下面的方法转换一下即可。
private Bitmap getBitmapFromDrawable(@DrawableRes int drawableId) {
Drawable drawable = ContextCompat.getDrawable(getContext(), drawableId);
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat) {
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");
}
}
网友评论