文档管理中心

自定义界面扫码如何实现扫码框

问题现象

扫码界面没有类似扫码框呈现。

解决措施

  1. 使用ArkTS在实时扫码界面画出需要的扫码框。

  2. 根据获得的码图位置信息确定码图是否在扫码框内(注意:需要将码图位置单位和扫码框位置单位保持一致,根据实际情况使用px或vp)。

  3. 当码图位置不在扫码框范围内时,在start的callback回调中执行rescan接口,即可继续扫码。

示例代码(仅供参考):

收起
自动换行
深色代码主题
复制
  1. import { customScan, scanBarcode } from '@kit.ScanKit';
  2. import { hilog } from '@kit.PerformanceAnalysisKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. // 例如XComponent设置的宽高为cameraWidth = 1080px, cameraHeight = 1920px
  5. let cameraWidth = 1080;
  6. let cameraHeight = 1920;
  7. // 自定义扫码框在屏幕中间 scanBox 为800px*800px,则扫码框相对XComponent的坐标left: 140px, top: 560px, right: 940px, bottom: 1360px
  8. let scanBoxWidth = 800;
  9. let scanBoxHeight = 800;
  10. let scanBox: scanBarcode.ScanCodeRect = {
  11. left: (cameraWidth - scanBoxWidth) / 2,
  12. top: (cameraHeight - scanBoxHeight) / 2,
  13. right: (cameraWidth + scanBoxWidth) / 2,
  14. bottom: (cameraHeight + scanBoxHeight) / 2
  15. };
  16. // 设置ViewControl参数
  17. let viewControl: customScan.ViewControl = {
  18. width: cameraWidth,
  19. height: cameraHeight,
  20. surfaceId: '123' // mock数据,实际需要从组件生成获取
  21. };
  22. try {
  23. customScan.start(viewControl, (err: BusinessError, data: Array<scanBarcode.ScanResult>) => {
  24. if (err) {
  25. // 扫码识别失败
  26. return;
  27. }
  28. if (data && data.length > 0) {
  29. for (let i = 0; i < data.length; i++) {
  30. // 例如:scanCodeRect是{ left: 150px, top: 400px, right: 450px, bottom: 700px }
  31. const scanCodeRect: scanBarcode.ScanCodeRect | undefined = data[i].scanCodeRect;
  32. if (scanCodeRect) {
  33. // 判断码图位置是否位于扫码框范围内
  34. if (scanCodeRect.left >= scanBox.left && scanCodeRect.top >= scanBox.top &&
  35. scanCodeRect.right <= scanBox.right &&
  36. scanCodeRect.bottom <= scanBox.bottom) {
  37. // 扫码成功,码图位置位于扫码框范围,根据业务需求处理扫码结果
  38. // ...
  39. } else {
  40. // 码图位置不在扫码框范围,继续扫码
  41. try {
  42. customScan.rescan();
  43. break;
  44. } catch (err) {
  45. hilog.error(0x0001, '[Scan Sample]', `Failed to rescan. Code: ${err.code}, message: ${err.message}`);
  46. }
  47. }
  48. }
  49. }
  50. }
  51. });
  52. } catch (err) {
  53. hilog.error(0x0001, '[Scan Sample]', `Failed to start customScan. Code: ${err.code}, message: ${err.message}`);
  54. }
请输入您想要搜索的关键词