##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##
目标:生成二维码,并且可通过扫码读取二维码信息。
知识点: QRCode:用于显示单个二维码的组件。 接口
QRCode(value: string)
value:二维码内容字符串。最大支持512个字符,若超出,则截取前512个字符。 说明:该字符串内容确保有效,不支持null、undefined以及空内容,当传入上述内容时,将生成无效二维码。
QRCode属性 color:设置二维码颜色。默认值:'#ff000000',且不跟随系统深浅色模式切换而修改。 backgroundColor:设置二维码背景颜色。默认值:Color.White,从API version 11开始,默认值改为'#ffffffff',且不跟随系统深浅色模式切换而修改。 contentOpacity:设置二维码内容颜色的不透明度。不透明度最小值为0,最大值为1。取值范围:[0, 1],超出取值范围按默认值处理。
scanBarcode (默认界面扫码) 本模块提供默认界面扫码能力。
- ScanResult:扫码结果。
- ScanCodeRect:码的位置信息。使用默认扫码接口(startScan和startScanForResult)不返回码位置。
- Point:点坐标,该坐标系左上角为{0,0}。
- ScanOptions:扫码、识码参数。
ScanResult属性
- scanType:码类型。
- originalValue:码识别内容结果。
- scanCodeRect:码识别位置信息。
- cornerPoints:码识别角点位置信息,返回QR Code四个角点。
ScanOptions属性
- scanTypes设置扫码类型,默认扫码ALL(全部码类型)。
- enableMultiMode是否开启多码识别,默认false。true:多码识别。false:单码识别。
- enableAlbum是否开启相册,默认true。true:开启相册扫码。false:关闭相册扫码。
scanBarcode.startScanForResult 通过配置参数调用默认界面扫码,使用Promise异步回调返回解码结果。需要在页面和组件的生命周期内调用。
scanBarcode.startScan 通过配置参数调用默认界面扫码,使用Promise异步回调返回扫码结果。
实战: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
})
}
}