往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
自定义界面扫码如何实现扫码框
问题现象
扫码界面没有类似扫码框呈现。
解决措施
- 使用ArkTS在实时扫码界面画出需要的扫码框。
- 根据获得的码图位置信息确定码图是否在扫码框内(注意:需要将码图位置单位和扫码框位置单位保持一致,根据实际情况使用px或vp)。
- 当码图位置不在扫码框范围内时,在customScan.start的callback回调中执行customScan.rescan接口,即可继续扫码。
示例代码(仅供参考):
import { customScan, scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
// 例如XComponent设置的宽高为cameraWidth = 1080px, cameraHeight = 1920px
let cameraWidth = 1080;
let cameraHeight = 1920;
// 自定义扫码框在屏幕中间 scanBox 为800px*800px,则扫码框相对xComponent的坐标left: 140px, top: 560px, right: 940px, bottom: 1360px
let scanBoxWidth = 800;
let scanBoxHeight = 800;
let scanBox: scanBarcode.ScanCodeRect = {
left: (cameraWidth - scanBoxWidth) / 2,
top: (cameraHeight - scanBoxHeight) / 2,
right: (cameraWidth + scanBoxWidth) / 2,
bottom: (cameraHeight + scanBoxHeight) / 2
}
// 设置ViewControl参数
let viewControl: customScan.ViewControl = {
width: cameraWidth,
height: cameraHeight,
surfaceId: '123' // mock数据,实际需要从组件生成获取
};
try {
customScan.start(viewControl, async (error: BusinessError, result: Array<scanBarcode.ScanResult>) => {
if (error) {
// 扫码识别失败
return;
}
// 例如:mock扫码结果返回的结果为第一个result[0] = { left: 150px, top: 400px, right: 450px, bottom: 700px }
let scanResult: scanBarcode.ScanCodeRect = {
left: 150,
top: 400,
right: 450,
bottom: 700
};
// 判断码图位置是否位于扫码框范围内
if (scanResult.left >= scanBox.left && scanResult.top >= scanBox.top && scanResult.right <= scanBox.right &&
scanResult.bottom <= scanBox.bottom) {
// 扫码成功,码图位置位于扫码框范围,根据业务需求处理扫码结果
} else {
// 码图位置不在扫码框范围,继续扫码
try {
customScan.rescan();
} catch (error) {
hilog.error(0x0001, '[Scan Sample]', `Failed to rescan. Code: ${error.code}, message: ${error.message}`);
}
}
});
} catch (error) {
hilog.error(0x0001, '[Scan Sample]', `Failed to start customScan. Code: ${error.code}, message: ${error.message}`);
}