HarmonyOS鸿蒙Next中Image组件不同状态的图标设置咨询
HarmonyOS鸿蒙Next中Image组件不同状态的图标设置咨询 现在有一个Image控件。控件,有点击态,禁用态,常规态,选择态等。
请问该怎么设置。
类比下面demo,不同状态设置于一个index,通过自定义方法获取图片资源,然后传入Image(),代码如下:
@Entry
@Component
struct Index {
getImage(index: number): Resource {
let image = $r('app.media.startIcon')
switch (index) {
case 0:
image = $r('app.media.icon')
break;
case 1:
image = $r('app.media.app_icon')
break;
case 2:
image = $r('app.media.ic_decrease')
break;
case 3:
image = $r('app.media.ic_empty')
break;
default:
break;
}
return image
}
build() {
Column() {
Image(this.getImage(3)).width(100).height(100)
}.width('100%').height('100%')
}
}
使用多态样式,在组件的StateStyles接口中,定义组件不同状态下的样式。
@Entry
@Component
struct StyleExample {
@State isEnable: boolean = true;
@Styles pressedStyles() {
.backgroundColor("#ED6F21")
.borderRadius(10)
.borderStyle(BorderStyle.Dashed)
.borderWidth(2)
.borderColor('#33000000')
.width(120)
.height(30)
.opacity(1)
}
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center}) {
Text("pressed")
.backgroundColor('#0A59F7')
.borderRadius(20)
.borderStyle(BorderStyle.Dotted)
.borderWidth(2)
.borderColor(Color.Red)
.width(100)
.height(25)
.opacity(1)
.fontSize(14)
.fontColor(Color.White)
.stateStyles({
pressed: this.pressedStyles
})
.margin({
bottom: 20
})
.textAlign(TextAlign.Center)
}
.width(350)
.height(300)
}
}
当前不支持原生Image组件这样,建议用封装一下,demo如下:
@Entry
@Component
struct MyComponent {
build() {
Column() {
image()
}
}
}
// 替代Image组件
@Component
struct image{
@Styles normalStyle() {
.backgroundImage($r("app.media.startIcon"))
}
@Styles pressedStyle() {
.backgroundImage($r("app.media.background"))
}
build() {
Column(){
}
.height("200px")
.width("200px")
.backgroundImageSize({width:'100%',height:'100%'})
.stateStyles({
normal: this.normalStyle,
pressed: this.pressedStyle,
})
}
}
更多关于HarmonyOS鸿蒙Next中Image组件不同状态的图标设置咨询的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
不同状态对uri赋值改变不可以吗
在HarmonyOS鸿蒙Next中,Image组件的不同状态图标设置可以通过ResourceTable和XML文件进行配置。首先,在resources/base/media目录下放置不同状态的图标资源,例如icon_normal.png和icon_pressed.png。然后在resources/base/element目录下的image_element.xml文件中定义不同状态的图标资源。使用<state>标签来定义不同状态,例如<state name="state_pressed" value="true"/>,并在<image>标签中引用这些状态资源。在代码中,通过Image组件的setState方法来切换不同状态的图标显示。这种方式可以实现根据组件的状态动态切换图标,提升用户体验。
在HarmonyOS鸿蒙Next中,Image组件支持通过state属性设置不同状态的图标。你可以使用state属性定义不同状态(如正常、按下、禁用等)下的图片资源。例如:
<Image
src="normal.png"
state="pressed:pressed.png,disabled:disabled.png"
/>
其中,normal.png为默认状态图片,pressed.png为按下状态图片,disabled.png为禁用状态图片。通过这种方式,可以实现按钮或图标在不同状态下的动态切换。

