完整的相机应用示例,支持拍照、录像、分辨率设置、旋转角度调整等功能
API级别: API 9+ | 项目路径: HarmonyOS_NEXT/Media/Camera
Camera示例是一个功能完整的相机应用,展示HarmonyOS的多媒体相机API使用方法。
import camera from '@ohos.multimedia.camera';
import prompt from '@ohos.promptAction';
private cameraModel: CameraModel = new CameraModel();
private mXComponentController: XComponentController = new XComponentController();
async aboutToAppear() {
// 申请权限
await grantPermission();
// 获取surfaceId
this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
// 初始化相机
this.cameraModel.initCamera(this.surfaceId);
}
XComponent({
id: 'componentId',
type: 'surface', // 必须设置为surface
controller: this.mXComponentController
})
.onLoad(() => {
this.mXComponentController.setXComponentSurfaceSize({
surfaceWidth: 640,
surfaceHeight: 480
});
this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
this.cameraModel.initCamera(this.surfaceId);
})
.width('100%')
.height('100%')
photoEvent() {
if (this.currentModel === CameraMode.modePhoto) {
prompt.showToast({ message: '拍照中...', duration: 200 });
this.cameraModel.takePicture();
}
}
videoEvent() {
if (!this.isRecording) {
this.timeShow = true;
this.textTimerController.reset();
this.textTimerController.start();
this.cameraModel.startVideo();
this.isRecording = true;
} else {
this.timeShow = false;
this.textTimerController.pause();
this.cameraModel.stopVideo();
this.isRecording = false;
}
}
| API | 说明 |
|---|---|
| camera.getCameraManager() | 获取相机管理器 |
| getSupportedCameras() | 获取支持的相机列表 |
| createPreviewOutput() | 创建预览输出 |
| createPhotoOutput() | 创建拍照输出 |
| createVideoOutput() | 创建视频输出 |
| takePicture() | 拍照 |
| startVideo()/stopVideo() | 开始/停止录像 |
| cameraRelease() | 释放相机资源 |
// module.json5
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.CAMERA"
},
{
"name": "ohos.permission.MICROPHONE"
},
{
"name": "ohos.permission.WRITE_MEDIA"
}
]
}
}
• 权限必须动态申请,不能只在配置文件中声明
• 页面退出时必须释放相机资源
• surfaceId需要在XComponent的onLoad回调中获取
• 需要考虑不同设备的相机能力差异
📎 官方仓库链接