获取位图矢量从绘制 [英] Getting Bitmap from vector drawable
问题描述
在我的申请,我必须设置一个大图标的通知。
LargeIcon必须是一个位图,我可绘是矢量图像(在Android的新功能,请参阅此链接一>)
问题是,当我试图去code的资源是一个矢量图像,我得到一个空返回。
In my application, I have to set a large icon for a notification. LargeIcon must be a Bitmap, and my drawables are vector images (the new feature in Android, see this link) The problem is when I try to decode a resource that is a vector image, I get a null returned.
下面是code的样本:
Here is the sample of code :
if (BitmapFactory.decodeResource(arg0.getResources(), R.drawable.vector_menu_objectifs) == null)
Log.d("ISNULL", "NULL");
else
Log.d("ISNULL", "NOT NULL");
在这个例子中,当我和一个正常的形象,为一为例更换PNG R.drawable.vector_menu_objectifs,结果不是空(我得到正确的位图)
是否有什么我失踪?
In this sample, when I replace R.drawable.vector_menu_objectifs with a "normal" image, a png for exemple, the result is not null (I get the correct bitmap) Is there something I'm missing?
推荐答案
您可以使用下面的方法:
You can use the following method:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
Bitmap 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);
return bitmap;
}
我有时结合起来:
which I sometimes combine with:
private static Bitmap getBitmap(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
这篇关于获取位图矢量从绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!