HarmonyOS 如何使用简单的api实现手电筒功能?

现在实现手电筒的方法是把相机流绘制到XComponent上去,然后把XComponent隐藏,再通过相机的session去控制闪光灯,是否有更好的实现方案?

阅读 639
1 个回答

示例参考如下:

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { camera } from '@kit.CameraKit';

let context = getContext(this) as common.BaseContext;

function setTorchMode(torchMode: camera.TorchMode): void {
  let cameraManager: camera.CameraManager = camera.getCameraManager(context);
  try {
    cameraManager.setTorchMode(torchMode);
  } catch (error) {
    // 失败返回错误码error.code并处理
    let err = error as BusinessError;
    console.error(`The setTorchMode call failed. error code: ${err.code}`);
  }
}

@Entry
@Component
struct Page9 {
  @State message: string = 'Hello World';
  @State Torch: boolean = true
  build() {
    Row() {
      Column() {
        Button() {
          Text("flash")
            .fontColor(Color.Black)
            .alignSelf(ItemAlign.Center)
            .onClick(() => {
              this.Torch = !this.Torch
              if (this.Torch) {
                setTorchMode(camera.TorchMode.ON)
              } else {
                setTorchMode(camera.TorchMode.OFF)
              }
            })
        }
        .width(100)
        .height(100)
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进