Iamge组件如何加载Graphic的资源图片?
在layout的xml文件中Image组件可以通过src直接应用graphic中的xml的图片资源,但是如何在代码中动态引用呢?因为要动态进行更改
image.setPixelMap()会报“ohos.media.image.SourceDataMalformedException: image decode failed”的错误,转成PixelMap类型也报上诉错误。
我使用的转pixelmap代码:
private PixelMap getGraphicPixelMap(int resourceId) throws IOException {
    InputStream source = null;
    PixelMap pixelmap = null;
    try {
        source = this.getResourceManager().getResource(resourceId);
        ImageSource imageSource = ImageSource.create(source, null);
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(100, 100);
        pixelmap = imageSource.createPixelmap(decodingOpts);
    } catch (IOException | NotExistException e) {
        e.getLocalizedMessage();
    } finally {
        assert source != null;
        source.close();
    }
    return pixelmap;
}
那如何在代码中动态应用graphic中xml类型图片资源呢?





















“image加载graphic中的xml的图片资源”楼主说的是矢量图吧。
目前我只知道一种办法:使用setBackground方法,代码如下,希望能帮到你。
1、xml中,需要设置宽高具体的数值,否则不显示(部分代码)
<Image
ohos:id="$+id:image"
ohos:height="50vp"
ohos:width="50vp"
ohos:background_element="$graphic:ic_home"/>
2、ability中代码设置(部分代码)
VectorElement vectorElement = new VectorElement(getContext(), ResourceTable.Graphic_ic_person);
image.setBackground(vectorElement);