0
点赞
收藏
分享

微信扫一扫

【HarmonyOS】根据文本内容动态测算文本控件宽高

【HarmonyOS】根据文本内容动态测算文本控件宽高

问题背景: 一般情况下,在鸿蒙里文本控件Text或者Span的宽高,我们都会设置固定宽高,或者根据内容自适应,不设置固定宽高。 但是在特殊场景下,例如,父组件的宽高需要根据子组件的内容动态设置宽高。或者是文本控件根据内容会有行数变化。都需要能动态根据文本控件的内容,测算出宽高。

解决方案:

使用MeasureText类的measureText接口实现该效果,根据文本内容获取到控件的宽度。函数入参,需要传入文本内容和字体大小即可。

文本内容是string类型,字体大小可以是number或者string,前者时为fp。一般字体大小使用px2fp进行转化。后者string时传入类似 “90px”的字符串。

该工具类还有个measureTextSize接口可以动态获取宽高。

DEMO实例:

/**
 * 动态测试文本控件行数
 */
@Entry
@Component
struct TextPage {
  
  private mTextFontSize: number = px2fp(42);
  private mLineHeight: number = px2vp(72);
  private mSysWidth: number = Utils.getSysWidth(); //获取系统宽度。从ability的onCreate函数中,通过windowStage获取。

  private mTextTestContent: string = "文本测试内容123456文本测试内容123456文本测试内容123456文本测试内容123456文本测试内容123456文本测试内容123456文本测试内容123456";

  @State mTextHeight: number = this.mLineHeight;

  aboutToappear(){
    this.mTextHeight = this.getChangeLineHeight();
  }

  private getChangeLineHeight(content: string, size: number): number {
  	let textWidth: number = MeasureText.measureText({ textContent: this.mTextTestContent, fontSize: this.mTextFontSize });
  	let targetNum: number = textWidth / this.mSysWidth;
  	return targetNum;
  }

  build() {
    Stack(){
      Text(this.mTextTestContent)
        .fontSize(this.mTextFontSize)
      	.width("100%")
      	.height(this.mTextHeight)
      	.backgroudColor(Color.Blue)
    }
     .width("100%")
     .height(this.mTextHeight)
     .backgroudColor(Color.Red)
  }
}

举报

相关推荐

0 条评论