Harmonyos5应用开发实战——摄影拍摄页面构建
文章概要
本文聚焦于HarmonyOS Next平台上摄影拍摄页面的开发实践。详细介绍了拍摄页面的整体布局搭建,包括权限请求、相机功能初始化、界面交互元素(如闪光灯、变焦、拍摄、切换摄像头等)的实现,为开发者在HarmonyOS Next环境下构建类似的拍摄页面提供了详细的参考。
核心功能及代码实现
1. 权限请求与相机初始化
在页面即将显示时,通过 abilityAccessCtrl
向用户请求相机权限,权限请求成功后调用 cameraShooting
函数初始化相机。同时,监听重力传感器,根据设备的倾斜角度调整拍摄方向。代码如下:
aboutToAppear() {
sensor.on(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {
let degree: number = -1;
degree = this.getCalDegree(data.x, data.y, data.z);
if (degree >= 0 && (degree <= 30 || degree >= 330)) {
this.rotation = camera.ImageRotation.ROTATION_0;
} else if (degree >= 60 && degree <= 120) {
this.rotation = camera.ImageRotation.ROTATION_270;
} else if (degree >= 150 && degree <= 210) {
this.rotation = camera.ImageRotation.ROTATION_180;
} else if (degree >= 240 && degree <= 300) {
this.rotation = camera.ImageRotation.ROTATION_90;
}
})
abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, this.cameraPermission).then(async () => {
zoomRatioRange = await cameraShooting(cameraPosition, surfaceId, context);
});
}
2. 界面交互元素 - 闪光灯控制
通过 Image
组件显示闪光灯图标,并绑定菜单,用户可以选择不同的闪光灯模式(关闭、打开、自动、常亮),点击相应选项时调用 switchFlash
函数设置闪光灯模式。代码如下:
Image(this.flashPic)
.height(CameraConstants.IMAGE_HEIGHT)
.margin(CameraConstants.MARGIN)
.visibility(this.isFront ? Visibility.Hidden : Visibility.Visible)
.bindMenu([
{
value: 'off',
action: (): void => {
this.flashPic = $r('app.media.ic_camera_public_flash_off');
this.switchFlash(camera.FlashMode.FLASH_MODE_CLOSE);
}
},
{
value: 'on',
action: (): void => {
this.flashPic = $r('app.media.ic_camera_public_flash_on');
this.switchFlash(camera.FlashMode.FLASH_MODE_OPEN);
}
},
{
value: 'auto',
action: (): void => {
this.flashPic = $r('app.media.ic_camera_public_flash_auto');
this.switchFlash(camera.FlashMode.FLASH_MODE_AUTO);
}
},
{
value: 'always_on',
action: (): void => {
this.flashPic = $r('app.media.ic_camera_public_flash_always_on');
this.switchFlash(camera.FlashMode.FLASH_MODE_ALWAYS_OPEN);
}
},
])