鸿蒙UI开发——隐私遮罩效果
1、概 述
如果我们希望对某些文字或图片做隐私遮罩处理,ArkUI为组件提供了一个属性可以方便的实现此效果,效果类似如下:
2、具体使用
我们在实现组件时,可以为组件添加obscured属性,用于为该属性设置隐私遮罩,接口定义如下:
// 设置组件内容的遮罩类型。
obscured(reasons: Array<ObscuredReasons>)
入参ObscuredReasons是一个枚举,目前只有一个值,如下:
PLACEHOLDER // 显示的数据为通用占位符。
需要注意:
-
目前支持的组件类型只有:Text文本组件、Image图片显示组件。
-
在为Image组件设置隐私遮罩时,最好设置一个默认宽高,因为如果图片是异步加载的,在图片加载完成前,如果没有默认宽高,会导致遮罩没有宽高信息。
-
如果Text组件设置了属性字符串,则隐私遮罩不生效(后续会有例子介绍)。
3、示例
👉🏻 step1:我们创建一个基本文本组件和图片显示组件,代码如下:
@Entry
@Component
struct ObscuredExample {
build() {
Row() {
Column() {
Text('欢迎加入【Harmony自习室】')
.fontSize(30)
.width(300)
.fontColor(Color.Black)
.border({ width: 1 })
Image($r('app.media.send_heart'))
.width('200px')
.height('200px')
}
.width('100%')
}
.height('100%')
}
}
效果如下:
👉🏻 step2:我们为刚刚创建的文本组件与图片组件添加隐私遮罩(12、16行)
@Entry
@Component
struct ObscuredExample {
build() {
Row() {
Column() {
Text('欢迎加入【Harmony自习室】')
.fontSize(30)
.width(300)
.fontColor(Color.Black)
.border({ width: 1 })
.obscured([ObscuredReasons.PLACEHOLDER])
Image($r('app.media.send_heart'))
.width('200px')
.height('200px')
.obscured([ObscuredReasons.PLACEHOLDER])
}
.width('100%')
}
.height('100%')
}
}
效果如下:
如果我们为Text组件设置了属性字符串,将不会生效隐私遮罩,代码如下:
@Entry
@Component
struct ObscuredExample {
fontStyle1: StyledString = new StyledString("欢迎加入【Harmony自习室】");
controller1: TextController = new TextController();
async onPageShow() {
this.controller1.setStyledString(this.fontStyle1)
}
build() {
Row() {
Column() {
// 显示属性字符串
Text(undefined, { controller: this.controller1 })
.obscured([ObscuredReasons.PLACEHOLDER])
}
.width('100%')
}
.height('100%')
}
}
效果如下: