鸿蒙应用示例:ArkTS UI 框架中的文本缩进技巧
作者:zhongcx
- 2024-10-12 广东
本文字数:2049 字
阅读完需:约 7 分钟
在开发基于 HarmonyOS 的应用程序时,我们可能会遇到需要对文本进行缩进的需求。本文将通过两个具体的例子来展示如何使用 ArkTS UI 框架实现这种效果。
方案一:利用获取空格宽度实现缩进
此方案通过测量单个空格的宽度来确定文本前需要添加多少个空格以达到所需的缩进效果。以下是具体的实现代码:
@Entry@Componentstruct Index { @State arr_01: Resource[] = [] @State arr_02: string[] = ['', '', '', ''] @State spaceWidth: number = 0 // 单个空格的宽度
build() { Scroll() { Column({ space: 10 }) { Text('方案一:利用获取空格宽度实现缩进') Text(' ').onAreaChange((_oldValue, newValue) => { this.spaceWidth = parseFloat('' + newValue.width) console.info(`单个空格的宽度为:${this.spaceWidth}px`) this.arr_01 = [$r("app.media.icon_0"), $r("app.media.icon_1"), $r("app.media.icon_2"), $r("app.media.icon_3")] }) ForEach(this.arr_01, (icon: Resource, index: number) => { Row({ space: 10 }) { Image($r('app.media.app_icon')) .width('40%') .height(80) .objectFit(ImageFit.Fill) .border({ radius: 10 }) Stack({ alignContent: Alignment.TopStart }) { Text(`${this.arr_02[index]}专升本2021华为开发者联盟欢迎您加入开发者大家庭专升本2021华为开发者联盟欢迎您加入开发者大家庭专升本2021华为开发者联盟欢迎您加入开发者大家庭`) .fontSize(16) .fontWeight(FontWeight.Bold) .maxLines(2) .lineHeight(24) .textOverflow({ overflow: TextOverflow.Ellipsis }) Image(icon) .height(20) .borderRadius(5) .onAreaChange((_oldValue, newValue) => { let iconWidth = parseFloat('' + newValue.width) console.info(`缩进开始于索引 ${index}`) console.info(`图标宽度为:${iconWidth}px`) let numSpaces = Math.ceil(iconWidth / this.spaceWidth) + 1 console.info(`计算出需要 ${numSpaces} 个空格进行缩进`) this.arr_02[index] = ' '.repeat(numSpaces) console.info(`更新后的缩进字符串为:[${this.arr_02[index]}]`) console.info(`缩进结束于索引 ${index}`) }) }.width('60%') }.width('100%') .padding({ left: 10, top: 10, right: 20 }) }) } }.width('100%').height('100%') }}
复制代码
方案二:利用 ContainerSpan 实现缩进
此方案使用 ContainerSpan 来将图像和其他容器嵌入文本流中,从而自然地实现缩进效果。以下是具体的实现代码:
@Entry@Componentstruct Index { @State arr_01: Resource[] = [$r("app.media.icon_0"), $r("app.media.icon_1"), $r("app.media.icon_2"), $r("app.media.icon_3")]
build() { Scroll() { Column({ space: 10 }) { Text('方案二:利用ContainerSpan实现缩进') ForEach(this.arr_01, (icon: Resource, _index: number) => { Row({ space: 10 }) { Image($r('app.media.app_icon')) .width('40%') .height(80) .objectFit(ImageFit.Fill) .border({ radius: 10 }) Stack({ alignContent: Alignment.TopStart }) { Text() { ContainerSpan() { ImageSpan(icon) .height(20) .borderRadius(5) Span('专升本2021华为开发者联盟欢迎您加入开发者大家庭专升本2021华为开发者联盟欢迎您加入开发者大家庭专升本2021华为开发者联盟欢迎您加入开发者大家庭') .fontSize(16) .fontWeight(FontWeight.Bold) .lineHeight(24) } }.maxLines(2) .textOverflow({ overflow: TextOverflow.Ellipsis }) }.width('60%') }.width('100%') .padding({ left: 10, top: 10, right: 20 }) }) } }.width('100%').height('100%') }}
复制代码
【结论】
以上两种方法都可以实现文本的缩进,但是它们各有优缺点。
方案一更加灵活,可以根据实际宽度动态调整缩进;
而方案二则更为简洁,适用于不需要频繁变化缩进的情况。开发者应根据具体应用场景选择最适合的方式。
【素材】
划线
评论
复制
发布于: 刚刚阅读数: 6
zhongcx
关注
还未添加个人签名 2024-09-27 加入
还未添加个人简介









评论