Objective: To generate a QR code and read its information by scanning the code.

Knowledge points:
QRCode: A component used to display a single QR code.
interface

QRCode(value: string)

value: QR code content string. The maximum support is 512 characters. If exceeded, the first 512 characters will be truncated.
Explanation: The string content is guaranteed to be valid and does not support null, undefined, or empty content. When the above content is passed in, an invalid QR code will be generated.

QRCode attribute
color: Set the color of the QR code. Default value: '# ff000000', And it does not follow the system's switching between light and dark modes for modification.
backgroundColor: Set the background color of the QR code. Default value: Color.White, Starting from API version 11, the default value has been changed to '#ffffff', and it does not change with the system's light and dark mode switching.
contentOpacity: Set the opacity of the color of the QR code content. The minimum and maximum opacity values are 0 and 1, respectively. Value range: [0, 1]. If it exceeds the value range, it will be treated as the default value.

ScanBarcode (default interface scan code)
This module provides default interface scanning capability.

  • ScanResult: Scan code result.
  • ScanCodeRect: Position information of the code. Using the default scanning interfaces (startScan and startScanForResult) does not return the code position.
  • Point: Point coordinates, the top left corner of the coordinate system is {0,0}.
  • ScanOptions: Scanning and code recognition parameters.

ScanResult attribute

  • ScanType: Code type.
  • OriginalValue: The result of code recognition content.
  • ScanCodeRect: Code recognition location information.
  • CornerPoints: Identify the position information of corner points and return the four corner points of the QR Code.

ScanOptions attribute

  • ScanTypes sets the scanning type, default scanning is ALL (all code types).
  • Whether enableMultiMode enables multi code recognition, defaults to false. true: Multi code recognition. false: Single code recognition.
  • Whether enableAlbum opens an album, defaults to true. true: Open the photo album and scan the QR code. false: Close the photo album and scan the QR code.

scanBarcode.startScanForResult
Call the default interface to scan the code by configuring parameters, and use Promise asynchronous callback to return the decoding result. It needs to be called within the lifecycle of the page and components.

scanBarcode.startScan
Call the default interface to scan the code by configuring parameters, and use Promise asynchronous callback to return the scan result.

Actual combat:ScanCodeDemoPage

import { scanBarcode, scanCore } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct ScanCodeDemoPage {
  codeMsg: string = '二维码信息通常为链接,以及json数据'
  @State getCodeMsg: string = ''

  build() {
    Column({ space: 10 }) {
      Text('二维码Demo')

      Text('生成二维码:')
      QRCode(this.codeMsg).width(140).height(140)

      Button('扫码').onClick(() => {
        // 构造启动扫码的入参options
        let options: scanBarcode.ScanOptions =
          { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };
        try {
          scanBarcode.startScan(options, (error: BusinessError, result: scanBarcode.ScanResult) => {
            // error回调监听,当扫码过程中出现错误打印报错并返回
            if (error) {
              hilog.error(0x0001, '[Scan Sample]',
                `Failed to get ScanResult by callback with options. Code: ${error.code}, message: ${error.message}`);
              return;
            }
            hilog.info(0x0001, '[Scan Sample]',
              `Succeeded in getting ScanResult by callback with options, result is ${JSON.stringify(result)}`);
            this.getCodeMsg = result.originalValue
          });
        } catch (error) {
          hilog.error(0x0001, '[Scan Sample]', `Failed to startScan. Code: ${error.code}, message: ${error.message}`);
        }
      })

      Text('扫码后得到的信息为:')
      Text(this.getCodeMsg)
    }
    .height('100%')
    .width('100%')
    .padding({
      top: 10,
      bottom: 10,
      right: 20,
      left: 20
    })
  }
}