Read the original article:How to Achieve Automatic Font Size Scaling and Ellipsis for Text
How to Achieve Automatic Font Size Scaling and Ellipsis for Text
Problem Description
How can the Text component automatically adjust the font size to fit the container when displaying text? When the font size is reduced to the specified minimum size and still cannot be fully displayed, how can it automatically trigger an ellipsis display?
Background Knowledge
-
ellipsisMode: Sets the position of the ellipsis. The
ellipsisModeproperty only takes effect in inline mode and must be used together withoverflowset toTextOverflow.Ellipsis. Setting theellipsisModeproperty alone will not have any effect. - maxFontSize: Sets the maximum font size for the text.
- minFontSize: Sets the minimum font size for the text.
Solution
To achieve the relationship between font size scaling and ellipsis triggering, follow these specific steps:
- When defining the text component, specify the maximum and minimum font size ranges simultaneously;
- Set size constraints for the parent container;
- Configure text overflow rules to implement single-line display and ellipsis strategy;
- Trigger the ellipsis logic when the text cannot be fully displayed even at the minimum font size.
Example code is as follows:
@Entry
@Component
struct TextDemo {
@State message: string = '';
build() {
Column({ space: 20 }) {
TextInput({ text: this.message })
.onChange((value: string) => {
// This callback is triggered when the text content changes.
this.message = value;
})
.margin({top:40})
.width('80%')
.height(40)
Row() {
Text('Big')
.width(30)
.height(30)
.backgroundColor(Color.Orange)
.fontSize(18)
Text(this.message)
.maxFontSize(20)
.minFontSize(10)
.constraintSize({
minWidth: 15,
maxWidth: '100%'
})
.ellipsisMode(EllipsisMode.END)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(1)
.textAlign(TextAlign.Center)
.fontColor(Color.White)
.fontWeight(500)
.layoutWeight(1)
.height(30)
Text('Small')
.width(30)
.height(30)
.backgroundColor(Color.Orange)
.fontSize(8)
}
.width('100%')
.height(30)
}
.height('100%')
.width('100%')
.padding(10)
}
}

Top comments (0)