简体   繁体   English

VectorDrawable createFromStream似乎不起作用

[英]VectorDrawable createFromStream does not seem to work

I am trying to load vector drawables from the assets. 我正在尝试从资产加载矢量可绘制对象。

It works fine when I use png files: 使用png文件时效果很好:

final String name = "image.png";
final InputStream stream = context.getAssets().open(name);
drawable = Drawable.createFromStream(stream, name);
stream.close();

I tried using VectorDrawable.createFromStream() and VectorDrawableCompat.createFromStream() but both always return null. 我尝试使用VectorDrawable.createFromStream()和VectorDrawableCompat.createFromStream(),但两者始终返回null。

When I add the vector drawable to the drawbles resources it can be loaded without a problem. 当我将矢量可绘制对象添加到可绘制资源中时,可以毫无问题地对其进行加载。

I also tried using the binary xml file which gets created when adding the vector file to the drawables resources. 我还尝试使用将矢量文件添加到drawables资源时创建的二进制xml文件。

I use API level 24 and Support libs 24.2.0 with Android 5.1.1 to test this. 我使用API​​级别24和带有Android 5.1.1的Support libs 24.2.0进行了测试。 It should work on Android 4.2 and later. 它应可在Android 4.2及更高版本上使用。

Does anyone know how to fix this? 有谁知道如何解决这一问题?

This issue could relate to this one: Load a vector drawable into imageview from sd card 此问题可能与此有关: 从SD卡将可绘制的矢量加载到imageview中

After looking at the Android source code I found a solution. 查看Android源代码后,我找到了解决方案。 The method createFromStream does not seem to support vector drawables. 方法createFromStream似乎不支持矢量可绘制对象。 Because it uses a BitmapFactory. 因为它使用BitmapFactory。

but we can load them as xml resource: 但是我们可以将它们作为xml资源加载:

final XmlResourceParser parser = context.getAssets().openXmlResourceParser("assets/folder/image.xml");
drawable = VectorDrawableCompat.createFromXml(context.getResources(), parser);

The image.xml musst be a precompiled binary xml file. image.xml必须是预编译的二进制xml文件。 You can extract them out of the generated apk file when you add the vector drawable to the drawable resources. 将可绘制矢量添加到可绘制资源时,可以将它们从生成的apk文件中提取出来。

The problem with this approach is, that it needs Android 5. But I need a working code for Android 4.2. 这种方法的问题是,它需要Android5。但是我需要适用于Android 4.2的有效代码。 Anyone an idea? 有人知道吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM