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

HarmonyOS
2024-12-19 17:23:27
浏览
收藏 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] 
                }
              }
分享
微博
QQ
微信
回复
2024-12-19 19:13:36
相关问题
自定义界面预览画面出现拉伸
2801浏览 • 1回复 待解决
HarmonyOS 自定义咨询
823浏览 • 1回复 待解决
HarmonyOS 如何自定义页面
898浏览 • 1回复 待解决
HarmonyOS PDF预览界面自定义
930浏览 • 1回复 待解决
HarmonyOS 自定义相机预览问题
1231浏览 • 1回复 待解决
HarmonyOS 自定义的恢复态API
779浏览 • 1回复 待解决
HarmonyOS 自定义相机预览拉伸问题
1193浏览 • 1回复 待解决
HarmonyOS 自定义功能
981浏览 • 1回复 待解决
HarmonyOS 自定义相机demo
1971浏览 • 1回复 待解决