HarmonyOS ScanKit自定义界面扫码,相机流无法预览

HarmonyOS
2024-12-19 17:23:27
788浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

参考:

// 导入功能涉及的权限申请、回调接口
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AsyncCallback,BusinessError } from '@kit.BasicServicesKit';
import { common,abilityAccessCtrl, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { scanCore, scanBarcode, customScan, detectBarcode } from '@kit.ScanKit';
import { router, promptAction, display } from '@kit.ArkUI';
import { picker } from '@kit.CoreFileKit';

@Entry
@Component
struct ScanQATest {
  @State userGrant: boolean = false
  @State surfaceId: string = ''
  @State isShowBack: boolean = false
  @State isFlashLightEnable: boolean = false
  @State isSensorLight:boolean = false
  // 设置预览流高度,默认单位:vp
  @State cameraHeight: number = 640
  // 设置预览流宽度,默认单位:vp
  @State cameraWidth: number = 360
  @State cameraOffsetX: number = 0
  @State cameraOffsetY: number = 0
  @State zoomValue: number = 1
  @State setZoomValue: number = 1
  @State scaleValue: number = 1
  @State pinchValue: number = 1
  @State displayHeight: number = 0
  @State displayWidth: number = 0
  private mXComponentController: XComponentController = new XComponentController()
  private TAG: string = '[customScanPage]'

  async showScanResult(result: Array<scanBarcode.ScanResult>) {
    if (result.length > 0) {
      // 获取到扫描结果后暂停相机流
      customScan.stop().then(() => {
        hilog.info(0x0001, this.TAG, 'Succeeded in stopping customScan by promise!');
      }).catch((error: BusinessError) => {
        hilog.error(0x0001, this.TAG,
          `Failed to stop customScan by promise. Code: ${error.code}, message: ${error.message}`);
      })

      // 使用toast显示出扫码结果
      promptAction.showToast({
        message: JSON.stringify(result),
        duration: 5000
      });
      this.isShowBack = true;
    }
  }

  async reqPermissionsFromUser(): Promise<number[]> {
    hilog.info(0x0001, this.TAG, 'reqPermissionsFromUser start');
    let context = getContext() as common.UIAbilityContext;
    let atManager = abilityAccessCtrl.createAtManager();
    let grantStatus = await atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']);
    return grantStatus.authResults;
  }

  // 申请相机权限
  async requestCameraPermission() {
    let grantStatus = await this.reqPermissionsFromUser();
    for (let i = 0; i < grantStatus.length; i++) {
      if (grantStatus[i] === 0) {
        // 用户授权,可以继续访问目标操作
        hilog.info(0x0001, this.TAG, 'Succeeded in getting permissions.');
        this.userGrant = true;
      }
    }
  }

  setDisplay() {
    // 默认竖屏
    let displayClass = display.getDefaultDisplaySync();
    this.displayHeight = px2vp(displayClass.height);
    this.displayWidth = px2vp(displayClass.width);
    let maxLen: number = Math.max(this.displayWidth, this.displayHeight);
    let minLen: number = Math.min(this.displayWidth, this.displayHeight);
    const RATIO: number = 16 / 9;
    this.cameraHeight = maxLen;
    this.cameraWidth = maxLen / RATIO;
    this.cameraOffsetX = (minLen - this.cameraWidth) / 2;
  }

  async onPageShow() {
    await this.requestCameraPermission();
    let options: scanBarcode.ScanOptions = {
      scanTypes: [scanCore.ScanType.ALL],
      enableMultiMode: true,
      enableAlbum: true
    }
    this.setDisplay();
    // 自定义初始化接口
    customScan.init(options);
  }

  async onPageHide() {
    // 页面消失或隐藏时,停止并释放相机流
    this.userGrant = false;
    this.isFlashLightEnable = false;
    this.isSensorLight = false;
    try {
      customScan.off('lightingFlash');
    } catch (error) {
      hilog.error(0x0001, this.TAG, `Failed to off lightingFlash. Code: ${error.code}, message: ${error.message}`);
    }
    await customScan.stop();
    // 自定义相机流释放接口
    customScan.release().then(() => {
      hilog.info(0x0001, this.TAG, 'Succeeded in releasing customScan by promise.');
    }).catch((error: BusinessError) => {
      hilog.error(0x0001, this.TAG,
        `Failed to release customScan by promise. Code: ${error.code}, message: ${error.message}`);
    })
  }

  // 自定义扫码界面的顶部返回按钮和扫码提示
  @Builder
  TopTool() {
    Column() {
      Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
        Text('返回')
          .onClick(async () => {
            router.back();
          })
      }.padding({ left: 24, right: 24, top: 40 })

      Column() {
        Text('扫描二维码/条形码')
        Text('对准二维码/条形码,即可自动扫描')
      }.margin({ left: 24, right: 24, top: 24 })
    }
    .height(146)
    .width('100%')
  }

  build() {
    Stack() {
      if (this.userGrant) {
        Column() {
          XComponent({
            id: 'componentId',
            type: 'surface',
            controller: this.mXComponentController
          })
            .onLoad(async () => {
              hilog.info(0x0001, this.TAG, 'Succeeded in loading, onLoad is called.');
              // 获取XComponent组件的surfaceId
              this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
              hilog.info(0x0001, this.TAG, `Succeeded in getting surfaceId: ${this.surfaceId}`);
              let viewControl: customScan.ViewControl = {
                width: this.cameraWidth,
                height: this.cameraHeight,
                surfaceId: this.surfaceId
              };
              // 启动相机进行扫码
              // 通过Promise方式回调
              customScan.start(viewControl)
                .then(async (result: Array<scanBarcode.ScanResult>) => {
                  // 处理扫码结果
                  this.showScanResult(result);
                });
              customScan.on('lightingFlash', (error, isLightingFlash) => {
                if (error) {
                  hilog.error(0x0001, this.TAG, `Failed to on lightingFlash. Code: ${error.code}, message: ${error.message}`);
                  return;
                }
                if (isLightingFlash) {
                  this.isFlashLightEnable = true;
                } else {
                  if (!customScan.getFlashLightStatus()) {
                    this.isFlashLightEnable = false;
                  }
                }
                this.isSensorLight = isLightingFlash;
              });
            })// XComponent宽、高,默认单位vp,支持px、lpx、vp
            .width(this.cameraWidth)
            .height(this.cameraHeight)
            .position({ x: this.cameraOffsetX, y: this.cameraOffsetY })
        }
        .height('100%')
        .width('100%')
      }

      Column() {
        this.TopTool()
        Column() {
        }
        .layoutWeight(1)
        .width('100%')

        Column() {
          Button('拉起图库')
            .backgroundColor('#0D9FFB')
            .fontSize(20)
            .fontColor('#ffea0909')
            .fontWeight(FontWeight.Normal)
            .align(Alignment.Center)
            .type(ButtonType.Capsule)
            .width('90%')
            .height(40)
            .margin({ top: 5, bottom: 5 })
            .onClick(() => {
              // 定义识码参数options
              let options: scanBarcode.ScanOptions = {
                scanTypes: [scanCore.ScanType.ALL],
                enableMultiMode: true,
                enableAlbum: true
              }
              // 通过选择模式拉起photoPicker界面,用户可以选择一个图片
              let photoOption = new picker.PhotoSelectOptions();
              photoOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
              photoOption.maxSelectNumber = 1;
              let photoPicker = new picker.PhotoViewPicker();
              photoPicker.select(photoOption).then((result) => {
                // 定义识码参数inputImage,其中uri为picker选择图片
                let inputImage: detectBarcode.InputImage = { uri: result.photoUris[0] 
                }
              }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
分享
微博
QQ
微信
回复
2024-12-19 19:13:36


相关问题
自定义界面预览画面出现拉伸
2588浏览 • 1回复 待解决
HarmonyOS 自定义咨询
648浏览 • 1回复 待解决
HarmonyOS 如何自定义页面
673浏览 • 1回复 待解决
HarmonyOS PDF预览界面自定义
714浏览 • 1回复 待解决
HarmonyOS 自定义相机预览问题
1022浏览 • 1回复 待解决
HarmonyOS 自定义相机预览拉伸问题
911浏览 • 1回复 待解决
HarmonyOS 自定义的恢复态API
597浏览 • 1回复 待解决
HarmonyOS 自定义功能
787浏览 • 1回复 待解决