从矢量图中获取位图 [英] Getting Bitmap from vector drawable
问题描述
在我的应用程序中,我必须为通知设置一个大图标.LargeIcon 必须是位图,而我的可绘制对象是矢量图像(Android 中的新功能,请参阅 此链接一>)问题是当我尝试解码矢量图像资源时,我得到了一个空值.
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.
这是代码示例:
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?
推荐答案
Checked on API: 17, 21, 23
Checked on 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;
}
更新:
项目梯度:
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
}
模块梯度:
android {
compileSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
vectorDrawables.useSupportLibrary = true
}
...
}
...
这篇关于从矢量图中获取位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!