从vector绘制获取位图

在我的应用程序中,我必须设置一个通知的大图标。 LargeIcon必须是一个位图,我的绘图是vector图像(Android中的新function,请参阅此链接 )问题是,当我尝试解码一个vector图像的资源,我得到一个空返回。

以下是代码示例:

if (BitmapFactory.decodeResource(arg0.getResources(), R.drawable.vector_menu_objectifs) == null) Log.d("ISNULL", "NULL"); else Log.d("ISNULL", "NOT NULL"); 

在这个示例中,当我用一个“普通”图像replaceR.drawable.vector_menu_objectifs,一个PNG为例,结果不是空(我得到正确的位图)是否有什么我失踪?

检查API:17,21,23

 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:

 dependencies { classpath 'com.android.tools.build:gradle:2.2.0-alpha5' } 

模块gradle:

 android { compileSdkVersion 23 buildToolsVersion '23.0.3' defaultConfig { minSdkVersion 16 targetSdkVersion 23 vectorDrawables.useSupportLibrary = true } ... } ... 

您可以使用以下方法:

 @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; } 

我有时把它们结合起来:

 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"); } } 

基于之前的答案,可以简化为像匹配VectorDrawable和BitmapDrawable,并至less与API 15兼容。

 public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) { Drawable drawable = ContextCompat.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的评论之后编辑了条件