【鸿蒙踩坑记录】解决:宽度固定时,数字超出如何缩小至完全显示

一、背景

在固定的宽度内,金额数字不固定并一行展示,如: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

最后:👏👏😊😊😊👍👍  

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值