效果圖:
官方API:
@ohos.measure (文本計算)
- 方式一
measure.measureTextSize
跟方式二使用一樣,只是API調用不同,可仔細查看官網
- 方式二
API 12+
@Preview
@Component
export struct CustomTextSpan {@State maxLines: number = 1// 臨時內容,用于計算@State contentTemp: string = ''// 折疊時 顯示內容@State showContent: string = ''// 是否展開@State isShow: boolean = false@Prop fontSize: number = 16@Prop fontColor: number | string = Color.Blue// 原始內容@Prop content: string ='被計算文被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容被計算文本內容'// 屏幕寬度 vp (真實手機)下面會動態計算屏幕寬度@State w: number = -1// MeasureUtils API12+提供的一種方式 也可以使用其他方式@State measureUtils: MeasureUtils = this.getUIContext().getMeasureUtils();@State computeHeight: SizeOptions = this.measureUtils.measureTextSize({textContent: this.content})@State computeLine: SizeOptions = this.measureUtils.measureTextSize({textContent: this.content})compute() {while (Number(this.computeHeight.height) > Number(this.computeLine.height)) {// 通過循環,每次減少一個字符長度,重新計算,直到高度滿足要求this.contentTemp = this.contentTemp.substring(0, this.contentTemp.length - 1);this.computeHeight = this.measureUtils.measureTextSize({textContent: this.contentTemp + '...' + '展開', // <按鈕文字>也要放入進行計算constraintWidth: px2vp(this.w),fontSize: this.fontSize});this.showContent = this.contentTemp + '...'}}aboutToAppear() {this.contentTemp = this.content// 真實手機動態計算屏幕的寬度this.w = display.getDefaultDisplaySync().widththis.computeHeight = this.measureUtils.measureTextSize({textContent: this.content,constraintWidth: px2vp(this.w),fontSize: this.fontSize})this.computeLine = this.measureUtils.measureTextSize({textContent: this.content,constraintWidth: px2vp(this.w),fontSize: this.fontSize,maxLines: this.maxLines})this.compute()}build() {Column() {if (!this.isShow) {Text() {Span(`${this.showContent}`)Span("展開").onClick(() => {this.isShow = !this.isShow}).fontColor(this.fontColor)}.width('100%').gesture(LongPressGesture().onAction((event: GestureEvent) => {promptAction.showToast({ message: "DSDASD" })}))}if (this.isShow) {Text(this.content).width('100%')Text("收起").width('100%').onClick(() => {this.isShow = !this.isShow}).width('100%').textAlign(TextAlign.End).fontColor(this.fontColor)}}.width('100%')}
}