方案一:
// 方案一 textWidthPx: SizeOptions = this.getUIContext().getMeasureUtils().measureTextSize({ textContent: this.message, fontSize: this.TextSize }); onPageShow(): void { const textWidthVp = this.getUIContext().px2vp(this.textWidthPx.width as number) + 2; this.lineWidth = textWidthVp + 'vp'; }
// 方案二 .onAreaChange((oldValue: Area, newValue: Area) => { console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`); this.lineWidth = `${Number(newValue.width) + 2}vp`; })
完整示例参考如下:
@Entry @Component struct TextLine { message: string = 'HelloWorld'; TextSize: number = 16; @State lineWidth: string = ''; // 方案一 textWidthPx: SizeOptions = this.getUIContext().getMeasureUtils().measureTextSize({ textContent: this.message, fontSize: this.TextSize }); onPageShow(): void { const textWidthVp = this.getUIContext().px2vp(this.textWidthPx.width as number) + 2; this.lineWidth = textWidthVp + 'vp'; } build() { RelativeContainer() { Text(this.message) .id('title') .fontSize(this.TextSize) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) // 方案二 .onAreaChange((oldValue: Area, newValue: Area) => { console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`); this.lineWidth = `${Number(newValue.width) + 2}vp`; }) Column() { } .width(this.lineWidth) .height(12) .alignRules({ center: { anchor: 'title', align: VerticalAlign.Center }, middle: { anchor: 'title', align: HorizontalAlign.Center } }) .linearGradient({ direction: GradientDirection.Left, colors: [['#a1c4fd', 0], ['#c2e9fb', 1]] }) .offset({ y: 8 }) .borderRadius(4) .zIndex(-1) } .height('100%') .width('100%') } }
方案二:
参考官方链接:Text组件如何给文本添加下划线。