温馨提示:本篇博客的详细代码已发布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下载运行哦!
@Component
export struct Avatar {
// 私有属性
private props: AvatarProps = {
shape: AvatarShape.CIRCLE,
size: AvatarSize.MEDIUM,
randomBgColor: false
}
@State private loadError: boolean = false
@State private bgColorValue: string = ''
}
状态说明:
props
:组件的主要配置属性,设置默认值loadError
:图片加载错误状态标记bgColorValue
:随机背景色的具体值// 生命周期
aboutToAppear() {
if (this.props.randomBgColor) {
this.bgColorValue = this.getRandomColor()
}
}
生命周期函数说明:
// 获取随机颜色
private getRandomColor(): string {
const colors = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae']
return colors[Math.floor(Math.random() * colors.length)]
}
实现说明:
// 获取显示大小
private getSize(): number {
if (typeof this.props.size === 'number') {
return this.props.size
}
const currentSize = this.props.size ?? AvatarSize.MEDIUM
switch (currentSize) {
case AvatarSize.MINI:
return 24
case AvatarSize.SMALL:
return 32
case AvatarSize.MEDIUM:
return 40
case AvatarSize.LARGE:
return 48
default:
return 40
}
}
实现说明:
// 背景渲染
if (this.props.randomBgColor || this.props.bgColor) {
Circle()
.fill(this.props.bgColor ?? this.bgColorValue)
.width('100%')
.height('100%')
}
实现说明:
// 内容渲染
if (this.props.text) {
// 文字模式
Text(this.props.text)
.fontSize(this.getSize() * 0.4)
.fontColor(Color.White)
} else if (this.props.icon) {
// 图标模式
Image(this.props.icon)
.width('60%')
.height('60%')
.objectFit(ImageFit.Contain)
} else if (this.props.src && !this.loadError) {
// 图片模式
Image(this.props.src)
.width('100%')
.height('100%')
.objectFit(ImageFit.Cover)
.onError(() => {
this.loadError = true
this.props.onError?.()
})
} else {
// 加载失败默认图标
Image($r("app.media.default_avatar"))
.width('100%')
.height('100%')
.objectFit(ImageFit.Cover)
}
渲染逻辑说明:
// 容器样式
Stack({ alignContent: Alignment.Center }) {
// 内容渲染
}
.width(this.getSize())
.height(this.getSize())
.borderRadius(this.props.shape === AvatarShape.SQUARE ? 4 : this.getSize() / 2)
样式说明:
下一篇教程将介绍Avatar组件的使用方法和样式定制,敬请期待!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。