根据下面网站DEMO信息
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/scan-customscan-api-V5
使用了customScan中的原样代码,代码如下:
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { scanBarcode, customScan } from '@kit.ScanKit';
@Entry
@Component
struct ScanQTCode {
// 设置预览流高度,默认单位:vp
@State cameraHeight: number = 640
// 设置预览流宽度,默认单位:vp
@State cameraWidth: number = 360
private mXComponentController: XComponentController = new XComponentController();
build() {
Stack() {
XComponent({
id: 'componentId',
type: 'surface',
controller: this.mXComponentController
})
.onLoad(() => {
hilog.info(0x0001, '[Scan Sample]', 'onLoad is called')
// 获取XComponent的surfaceId
let surfaceId: string = this.mXComponentController.getXComponentSurfaceId();
hilog.info(0x0001, 'viewControl', `onLoad surfaceId: ${surfaceId}`);
// 设置ViewControl相应字段
let viewControl: customScan.ViewControl = {
width: this.cameraWidth,
height: this.cameraHeight,
surfaceId: surfaceId
};
try {
customScan.start(viewControl, (error: BusinessError, scanResult: Array<scanBarcode.ScanResult>) => {
if (error) {
hilog.error(0x0001, '[Scan Sample]', 'start failed , error: %{public}s', JSON.stringify(error))
return;
}
hilog.info(0x0001, '[Scan Sample]', 'callback scan result: %{public}s', JSON.stringify(scanResult))
});
} catch (error) {
hilog.error(0x0001, '[Scan Sample]', 'start failed , error: %{public}s', JSON.stringify(error))
}
})
// 预览流宽、高,默认单位vp,支持px、lpx、vp
.height(this.cameraHeight)
.width(this.cameraWidth)
.position({ x: 0, y: 0 })
}
.alignContent(Alignment.Bottom)
.height('100%')
.width('100%')
.position({ x: 0, y: 0 })
}
};
API参考里面给的是部分的代码不是整个端到端的流程。当前代码的问题是没有申请相机的权限。
可以参考自定义扫码指南查看
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/scan-customscan-V5
几个要点:
2.拉起自定义扫码界面时需要动态申请相机的权限,等待用户授权
4.获取扫码结果
附权限声明module.json5: