大家好,我是 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) | 同左 |
四、避坑指南
- 尺寸陷阱
字節數組生成的二維碼必須滿足width=height,否則拋出202(參數非法)錯誤。 -
糾錯等級選擇
LEVEL_L(15%糾錯):數據≤2048字節 → 容錯高/密度低LEVEL_H(30%糾錯):數據≤1024字節 → 容錯低/密度高
交通卡推薦LEVEL_Q(25%容錯)
- 內容超長處理
若文本超限(如Code39超80字節),需分段生成或改用QR Code。 -
渲染優化
使用Image組件顯示PixelMap時,添加背景色提升識別率:Image(this.pixelMap) .backgroundColor(Color.White) // 強制白底通過合理選擇生成方式並遵守參數規範,可滿足零售、交通、支付等高可靠性場景需求,實際開發中建議參考華為官方示例工程驗證設備兼容性。