鸿蒙NEXT版实战开发:自定义界面扫码如何实现扫码框?

往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)


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

问题现象

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

解决措施

  1. 使用ArkTS在实时扫码界面画出需要的扫码框。
  2. 根据获得的码图位置信息确定码图是否在扫码框内(注意:需要将码图位置单位和扫码框位置单位保持一致,根据实际情况使用px或vp)。
  3. 当码图位置不在扫码框范围内时,在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}`);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值