分层图标处理
场景介绍
适用于图标为分层资源,且图标展示风格要与华为HarmonyOS Design System设计风格一致的应用场景。
开发步骤
-
设置分层图标。
将前景资源和背景资源,放到entry\src\main\resources\base\media下,在该目录创建一个json文件(例如:drawable.json),内容为
{
"layered-image":
{
"background" : "$media:background", // 背景图
"foreground" : "$media:foreground" // 前景图
}
}
- 将图标处理的相关类添加至工程。
import { LayeredDrawableDescriptor } from '@kit.ArkUI';
import { hdsDrawable } from '@kit.UIDesignKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { resourceManager } from '@kit.LocalizationKit';
- 简单配置页面的布局,调用分层图标接口获取处理后的图标信息,也可以调用异步批量处理接口。
@Entry
@Component
struct Index{
bundleName: string = 'com.example.uidesignkit';
resManager: resourceManager.ResourceManager | undefined = undefined;
layeredDrawableDescriptor: LayeredDrawableDescriptor | undefined = undefined;
@State layeredIconsResult: Array<hdsDrawable.ProcessedIcon> = [];
build() {
Column() {
Column() {
Text('getHdsLayeredIcon')
.fontWeight(FontWeight.Bold)
.fontSize(16)
.margin(5)
Image(this.getHdsLayeredIcon())
.width(48)
.height(48)
}
.margin(20)
Text('getHdsLayeredIcons')
.fontWeight(FontWeight.Bold)
.fontSize(16)
.margin(5)
List() {
ForEach(this.layeredIconsResult,
(item: hdsDrawable.ProcessedIcon, index?: number) => {
ListItem() {
Column() {
Text(item.bundleName)
.fontWeight(FontWeight.Medium)
.fontSize(16)
.margin(5)
Image(item.pixelMap)
.width(48)
.height(48)
}
.margin(15)
}
.width('100%')
}, (item: string) => item.toString())
}
.scrollBar(BarState.On)
.height('60%')
}
.height('100%')
.width('100%')
}
aboutToAppear(): void {
this.resManager = getContext().resourceManager;
if (!this.resManager) {
return;
}
this.layeredDrawableDescriptor = (this.resManager.getDrawableDescriptor($r('app.media.drawable')
.id)) as LayeredDrawableDescriptor;
this.getHdsLayeredIcons();
}
private getHdsLayeredIcon(): image.PixelMap | null {
try {
return hdsDrawable.getHdsLayeredIcon(this.bundleName, this.layeredDrawableDescriptor, 48, true);
} catch (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`getHdsLayeredIcon failed, code: ${code}, message: ${message}`);
return null;
}
}
private getHdsLayeredIcons(): void {
if (!this.layeredDrawableDescriptor) {
console.error(`getHdsLayeredIcons layeredDrawable