一、背景
在固定的宽度内,金额数字不固定并一行展示,如:133.12,13071067.33,当金额超出固定宽度时,金额缩小至完全显示
二、实现方法
2.1、方法一
官网文档指引:文档中心
给 Text 组件增加 .maxLines(1)、.maxFontSize(16)、.minFontSize(10) 这三个属性来让文本自适应大小
2.1.1、场景一
当价格符合与价格小数点前后的字号都一致时,可以直接使用Text组件的以上三种属性
2.1.2、具体代码
@Entry
@Component
struct Index {
build() {
Column({ space: 10 }) {
Text('¥133.12')
.width(80)
.textAlign(TextAlign.Center)
.borderWidth(1)
.minFontSize(10)
.maxFontSize(16)
.maxLines(1)
Text('¥13071067.33')
.width(80)
.textAlign(TextAlign.Center)
.borderWidth(1)
.minFontSize(10)
.maxFontSize(16)
.maxLines(1)
}.width('100%').margin({ top: 100 })
}
}
2.1.3、具体效果
备注:文本最大显示字号与文本最小显示字号,根据需求来设定
第一个文本在宽度内,正常显示最大字号
第二个文本超出宽度,则显示最小字号
2.2、方法二
使用@ohos.measure (文本计算),计算文本宽度
官网文档指引:文档中心
2.2.1、场景二
当价格符合与价格小数点前后的字号不一致时,可以使用此方法
2.2.2、具体代码
import { MeasureText } from '@kit.ArkUI'
@Entry
@Component
struct Index {
@State textWidth: number = 80 //文本宽度
@State centreTextWidth: number = this.textWidth - 20 //小数点前面数字
getTextWidth(textContent: string, fontSize: number | string = 14): number {
if (!textContent) {
return 0
}
const width: number = MeasureText.measureText({
textContent: textContent,
fontSize: fontSize
})
return px2vp(width)
}
build() {
Column({ space: 10 }) {
Text() {
Span('¥').fontSize(12)
Span('133').fontSize(this.getTextWidth('133') > this.centreTextWidth ? 10 : 16)
Span('.12').fontSize(12)
}
.borderWidth(1).width(this.textWidth).textAlign(TextAlign.Center)
Text() {
Span('¥').fontSize(12)
Span('13071067').fontSize(this.getTextWidth('13071067') > this.centreTextWidth ? 10 : 16)
Span('.33').fontSize(12)
}
.borderWidth(1).width(this.textWidth).textAlign(TextAlign.Center)
}.width('100%').margin({ top: 100 })
}
}
2.2.2、实际效果
🚀🚀🚀 踩坑不易,还希望各位大佬支持一下
📃 我的土拨鼠开源项目:
✍Gitee开源项目地址👉:https://gitee.com/cheinlu/groundhog-charging-system
✍GitHub开源项目地址👉:https://github.com/cheinlu/groundhog-charging-system
📃 我的鸿蒙NEXT轮播图开源组件:https://gitee.com/cheinlu/harmony-os-next-swiper
最后:👏👏😊😊😊👍👍