DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Achieve Automatic Font Size Scaling and Ellipsis for Text

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 ellipsisMode property only takes effect in inline mode and must be used together with overflow set to TextOverflow.Ellipsis. Setting the ellipsisMode property 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:

  1. When defining the text component, specify the maximum and minimum font size ranges simultaneously;
  2. Set size constraints for the parent container;
  3. Configure text overflow rules to implement single-line display and ellipsis strategy;
  4. 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)
  }
}
Enter fullscreen mode Exit fullscreen mode

Verification Result

output4.gif

Written by Emrecan Karakas

Top comments (0)