效果图:
官方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%')}
}