如何在自定义组件HarmonyOS中获取PNG格式图标作为属性

问题描述

我正在使用 Java SDK 在 HarmonyOS 中创建一个自定义组件,我需要一个属性来从 xml 布局文件获取元素(即 VectorElement 或 png 格式图标)作为输入。

例如:

ohos:sliderIcon="$graphic:custom_icon" (VectorElement)
ohos:sliderIcon="$media:ic_arrow"      (PNG format icon)

现在我在这样的自定义组件类中获取元素

Element sliderIcon = attrSet.getAttr(Attribute.SLIDER_ICON).isPresent()
                    ? attrSet.getAttr(Attribute.SLIDER_ICON).get().getElement()
                    : new VectorElement(getContext(),ResourceTable.Graphic_slidetoact_ic_arrow);

但是,以上代码仅适用于 VectorElement 图标,不适用于 PNG 格式图标。

我可以在运行时从 java 代码设置 VectorElement 和 PNG 格式图标,如下所示:

对于向量元素:

Element sliderIcon = new VectorElement(getContext(),ResourceTable.Graphic_custom_icon);

对于 PNG 格式图标:

//You can set png format icon using PixelMapElement.
     try {
            Element sliderIcon = new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_arrow));
     } catch (IOException | NotExistException e) {
            e.printstacktrace();
     } 

所以我的问题是

如何在自定义组件中获取PNG格式图标作为属性

如何获取传递元素的资源/引用ID?

解决方法

刚刚试过你的方法通过const a = async() => { const res = await getFirstHelloWorld() return res } a().then((data) => { console.log('got result:',data) }); 得到pixelMap

PixelMapElement

PixelMapElement pixelMapElement = (PixelMapElement) attrSet.getAttr("sliderIcon").get().getElement(); PixelMap pixelMap = pixelMapElement.getPixelMap(); 方法中测试并证明可用。

onDraw