1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import CustomScanViewModel from '../viewmodel/CustomScanViewModel'; 17import CommonConstants from '../common/constants/CommonConstants'; 18import { logger } from '../common/util/Logger'; 19 20/** 21 * 扫码相机流组件 22 * 实现步骤: 23 * 1.使用XComponent展示相机流内容 24 * 2.XComponent加载完成之后开启扫码服务 25 * 3.监控应用前后台切换、折叠屏状态变更,释放和重启扫码服务 26 */ 27@Component 28export default struct CustomScanCameraComp { 29 // 自定义扫码vm实例 30 @Consume('customScanVM') customScanVM: CustomScanViewModel; 31 // 相机流展示组件控制器 32 private cameraSurfaceController: XComponentController = new XComponentController(); 33 34 aboutToAppear() { 35 // 注册屏幕状态监听(仅折叠屏) 36 this.customScanVM.regDisplayListener(); 37 // 注册XComp尺寸修改回调 38 this.customScanVM.regXCompSizeUpdateListener((width: number, height: number, offsetX: number, offsetY: number) => { 39 this.updateCameraSurfaceSize(width, height, offsetX, offsetY); 40 }); 41 } 42 43 aboutToDisappear() { 44 // 释放相机流 45 this.customScanVM.initScanData(); 46 47 this.customScanVM.releaseCustomScan(); 48 // 清除surfaceId 49 this.customScanVM.surfaceId = ''; 50 } 51 52 53 build() { 54 Column() { 55 // TODO:知识点:相机流显示依赖XComponent 56 XComponent({ 57 type: XComponentType.SURFACE, 58 controller: this.cameraSurfaceController 59 }) 60 .onLoad(() => { 61 // TODO:知识点:customScan依赖XComponent组件的surfaceId,对图像进行扫描 62 this.customScanVM.surfaceId = this.cameraSurfaceController.getXComponentSurfaceId(); 63 // TODO:知识点:初始化XComponent组件的surface流的尺寸 64 this.updateCameraSurfaceSize(this.customScanVM.cameraCompWidth, this.customScanVM.cameraCompHeight 65 , this.customScanVM.cameraCompOffsetX, this.customScanVM.cameraCompOffsetY); 66 // TODO:知识点:XComponent加载完成后,启动相机进行扫码 67 this.customScanVM.initCustomScan(); 68 }) 69 .clip(true) 70 .expandSafeArea([SafeAreaType.SYSTEM],[SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) 71 } 72 .height('100%') 73 .width('100%') 74 } 75 76 /** 77 * 动态更新XComponent的Suerface尺寸 78 * @param {number} width 新宽度 79 * @param {number} height 新高度 80 * @returns {void} 81 */ 82 updateCameraSurfaceSize(width: number, height: number, offsetX: number, offsetY: number): void { 83 this.cameraSurfaceController.setXComponentSurfaceRect({ 84 offsetX: vp2px(offsetX), 85 offsetY: vp2px(offsetY), 86 surfaceWidth: vp2px(width), 87 surfaceHeight: vp2px(height), 88 }) 89 90 logger.info(`setXComponentSurfaceRect: ${width}, ${height}`); 91 } 92} 93