DEV Community

Cover image for Summary of Methods for Generating QR Codes from Strings and Images, Getting Text Line Counts
kouwei qing
kouwei qing

Posted on

Summary of Methods for Generating QR Codes from Strings and Images, Getting Text Line Counts

[Daily HarmonyOS Next Knowledge] Summary of Methods for Generating QR Codes from Strings and Images, Getting Text Line Counts, and Exiting Edit State in Input Boxes

1. How to replace the icon in the pull-down refresh with text in HarmonyOS?

Demo for hiding the icon and displaying text:

@Entry
@Component
struct RefreshExample {
  @State isRefreshing: boolean = false
  @State arr: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

  @Builder
  customRefreshComponent() {
    Stack() {
      Row() {
        // Hide the icon
        // LoadingProgress().height(32)
        Text("正在刷新...").fontSize(16).margin({ left: 20 })
      }
      .alignItems(VerticalAlign.Center)
    }
    .width("100%")
    .align(Alignment.Center)
  }

  build() {
    Column() {
      Refresh({ refreshing: $$this.isRefreshing, builder: this.customRefreshComponent() }) {
        List() {
          ForEach(this.arr, (item: string) => {
            ListItem() {
              Text('' + item)
                .width('100%')
                .height(100)
                .fontSize(16)
                .textAlign(TextAlign.Center)
                .borderRadius(10)
                .backgroundColor(0xFFFFFF)
            }
          }, (item: string) => item)
        }
        .onScrollIndex((first: number) => {
          console.info(first.toString())
        })
        .width('100%')
        .height('100%')
        .divider({ strokeWidth: 1, color: Color.Yellow, startMargin: 10, endMargin: 10 })
        .scrollBar(BarState.Off)
      }
      .onStateChange((refreshStatus: RefreshStatus) => {
        console.info('Refresh onStatueChange state is ' + refreshStatus)
      })
      .onRefreshing(() => {
        setTimeout(() => {
          this.isRefreshing = false
        }, 2000)
        console.log('onRefreshing test')
      })
      .backgroundColor(0x89CFF0)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

2. How to set a fixed light mode in HarmonyOS?

You can actively set the light/dark style of the application. Once set, the application's mode will not change with the system.

Reference: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-light-dark-color-adaptation-V5#section19361879317

By default, the application follows the system's light/dark mode. To fix the mode:

onCreate(): void {
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
}
Enter fullscreen mode Exit fullscreen mode

System default judgment rules:

  1. If the application explicitly sets the mode using setColorMode, that setting takes precedence.
  2. If setColorMode is not called:
    • If the application has dark resources in the dark directory, system components will automatically switch to dark mode.
    • If no dark resources exist, system components will remain in light mode even when the system is in dark mode.

To ensure the application follows the system's light/dark mode when using only system components/colors:

onCreate(): void {
  this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
}
Enter fullscreen mode Exit fullscreen mode

3. How to generate a QR code from a string and image in HarmonyOS?

Generate a QR code from a string and image that can be scanned and decoded.

Use the QRCode component:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-qrcode-V5

The QR code content is a string (max 256 characters; longer strings will be truncated).

4. How to get the number of text lines displayed in a HarmonyOS Text component?

Get the line count to adjust the layout dynamically.

The @ohos.measure module returns text width/height but not the line count directly. Calculate it based on your scenario:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-measure-V5


// Scenario 1: Apply different styles when text exceeds a specific line count (e.g., 3 lines)
let textSize: SizeOptions = measure.measureTextSize({ textContent: this.message, fontSize: 24, constraintWidth: 300 });
let textSize2: SizeOptions = measure.measureTextSize({ textContent: this.message, fontSize: 24, maxLines: 3, constraintWidth: 300 });
// If textSize.height > textSize2.height, the text exceeds 3 lines. Handle accordingly.

// Scenario 2: Reserve appropriate height before rendering
import measure from '@ohos.measure'

@Entry
@Component
struct Index {
  @State textSize: SizeOptions = { width: 0, height: 0 }
  @State message: string = 'Very long text...';

  aboutToAppear(): void {
    this.textSize = measure.measureTextSize({
      textContent: this.message, fontSize: 14, constraintWidth: 300
    })
    console.log(JSON.stringify(this.textSize))
  }

  build() {
    Row() {
      Swiper() {
        Row() {
          Text(this.message)
            .fontSize(14)
            .width(300)
        }
        .backgroundColor(Color.Yellow)
        .width(300)
        .height(px2vp(Number(this.textSize.height)))
      }
    }
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

5. How to make an InputText lose focus and exit the editing state in HarmonyOS?

Use stopEditing() to dismiss the keyboard:

@Entry
@Component
struct TextInputExample {
  controller: TextInputController = new TextInputController()
  @State inputValue: string = ""

  build() {
    Column() {
      TextInput({ text: this.inputValue, placeholder: 'input your word…', controller: this.controller })
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .caretColor(Color.Blue)
        .width('95%')
        .height(40)
        .margin(20)
        .fontSize(14)
        .fontColor(Color.Black)
        .onChange((value: string) => {
          this.inputValue = value
        })
    }
    .width('100%')
    .height('100%')
    .onClick(() => {
      this.controller.stopEditing()
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)