【鸿蒙开发实战篇】鸿蒙6开发中,通过文本和字节数组生成码图案例

62 阅读2分钟

大家好,我是 V 哥。

生成码图在很多应用中都很常见,今天的内容来给大家介绍鸿蒙6.0开发中通过文本/字节数组生成码图的详细案例解析,结合典型业务场景和技术实现要点:

联系V哥获取 鸿蒙学习资料


一、文本生成码图案例:商品条码生成(EAN-13)

业务场景
零售应用中为商品生成标准条码,用于库存管理和POS扫码结算。
技术实现

// 导入模块
import { generateBarcode } from '@kit.ScanKit';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct ProductBarcode {
  @State pixelMap: image.PixelMap | undefined = undefined

  build() {
    Column() {
      Button('生成商品条码')
        .onClick(() => {
          // EAN-13规范:12位数字,首位非0
          const content: string = "694251983457"; 
          const options: generateBarcode.CreateOptions = {
            type: generateBarcode.ScanType.EAN_13, // 指定条码类型
            width: 300,  // 宽度需在[200,4096]范围内
            height: 150, // 高度可不等于宽度(条码为矩形)
            margin: 2    // 边距范围[1,10]
          };
          // 生成并渲染
          generateBarcode.createBarcode(content, options)
            .then((pixelMap: image.PixelMap) => {
              this.pixelMap = pixelMap;
            })
            .catch((error: BusinessError) => {
              console.error(`生成失败: ${error.code}`);
            });
        })
      // 显示生成的条码
      if (this.pixelMap) {
        Image(this.pixelMap)
          .width(300)
          .height(150)
      }
    }
  }
}

关键约束

参数要求
内容长度12位数字
首位数字禁止为0
码类型ScanType.EAN_13
尺寸范围width/height ∈ [200,4096]

二、字节数组生成码图案例:交通卡二维码 业务场景
地铁APP生成加密的交通卡二维码,闸机设备专用解码器识别。
技术实现

// 导入模块(需包含buffer)
import { generateBarcode } from '@kit.ScanKit';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct TransportCard {
  @State qrCode: image.PixelMap | undefined = undefined

  build() {
    Column() {
      Button('生成交通卡二维码')
        .onClick(() => {
          // 1. 准备字节数组(加密数据)
          const hexData: string = "0177C10DD10F776860..."; // 16进制字符串
          const contentBuffer: ArrayBuffer = buffer.from(hexData, 'hex').buffer;
          
          // 2. 配置参数(仅支持QR Code)
          const options: generateBarcode.CreateOptions = {
            type: generateBarcode.ScanType.QR_CODE,
            width: 300,   // 需满足 width=height
            height: 300,  // 正方形二维码
            errorCorrectionLevel: generateBarcode.ErrorCorrectionLevel.LEVEL_Q // 25%纠错
          };
          
          // 3. 生成二维码
          generateBarcode.createBarcode(contentBuffer, options)
            .then((pixelMap: image.PixelMap) => {
              this.qrCode = pixelMap;
            })
            .catch((error: BusinessError) => {
              console.error(`生成失败: ${error.code}`);
            });
        })
      // 显示二维码
      if (this.qrCode) {
        Image(this.qrCode)
          .width(300)
          .height(300)
      }
    }
  }
}

核心限制

参数要求
数据类型ArrayBuffer(字节数组)
唯一支持码类型ScanType.QR_CODE
纠错等级与长度关系LEVEL_Q ≤ 1536字节
尺寸要求width必须等于height

三、技术对比与选型建议

维度文本生成字节数组生成
适用场景明文字符(网址、ID等)加密数据/二进制协议(如交通卡)
支持码类型13种(含QR/EAN/Code128等)仅QR Code
数据限制按码类型限制长度(如QR≤512字符)按纠错等级限制字节长度
颜色要求建议黑码白底(对比度>70%)同左
设备兼容性全设备(Phone/Tablet/Wearable/TV)同左

四、避坑指南

  1. 尺寸陷阱
    字节数组生成的二维码必须满足 width=height,否则抛出202(参数非法)错误。

  2. 纠错等级选择

    • LEVEL_L(15%纠错):数据≤2048字节 → 容错高/密度低
    • LEVEL_H(30%纠错):数据≤1024字节 → 容错低/密度高
      交通卡推荐LEVEL_Q(25%容错)
  3. 内容超长处理
    若文本超限(如Code39超80字节),需分段生成或改用QR Code。

  4. 渲染优化
    使用Image组件显示PixelMap时,添加背景色提升识别率:

   Image(this.pixelMap)
     .backgroundColor(Color.White) // 强制白底

通过合理选择生成方式并遵守参数规范,可满足零售、交通、支付等高可靠性场景需求,实际开发中建议参考华为官方示例工程验证设备兼容性。