画面布局初始化
MainAbilittySlice的初始化代码如下:
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
initComponents();
}
代码中只是调用了如下的组件初始化代码:
private void initComponents() {
Button iniCameraButton = (Button)findComponentById(ResourceTable.Id_ini_camera);
iniCameraButton.setClickedListener(Component->initSurface());
Button takePhotoButton = (Button) findComponentById(ResourceTable.Id_tack_picture_btn);
takePhotoButton.setClickedListener(this::takeSingleCapture);
takePhotoButton.setLongClickedListener(this::takeMultiCapture);
}
目前这段代码只是为两个按钮指派功能。其中【初始化】按钮的功能如下:
private void initSurface() {
getWindow().setTransparent(true);
DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig(
ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
surfaceProvider = new SurfaceProvider(this);
surfaceProvider.setLayoutConfig(params);
surfaceProvider.pinToZTop(false);
surfaceProvider.getSurfaceOps().get().addCallback(new SurfaceCallBack());
surfaceContainer = (ComponentContainer) findComponentById(ResourceTable.Id_surface_container);
surfaceContainer.addComponent(surfaceProvider);
}
它的功能是初始化相机,有一点需要注意的是:构建params时使用的参数必须和前一篇文章中说明的布局文件中为id:surface_container指定的属性相同。
当初始化过程结束后,下面的回调函数会被执行:
private class SurfaceCallBack implements SurfaceOps.Callback {
@Override
public void surfaceCreated(SurfaceOps callbackSurfaceOps) {
openCamera();
}
@Override
public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
}
}
的那个surface被成功创建之后,就可以打开相机了:
private void openCamera() {
imageReceiver = ImageReceiver.create(SCREEN_WIDTH, SCREEN_HEIGHT, ImageFormat.JPEG, IMAGE_RCV_CAPACITY);
imageReceiver.setImageArrivalListener(this::saveImage);
CameraKit cameraKit = CameraKit.getInstance(getApplicationContext());
String[] cameraList = cameraKit.getCameraIds();
String cameraId = cameraList.length > 1 && isCameraFront ? cameraList[1] : cameraList[0];
CameraStateCallbackImpl cameraStateCallback = new CameraStateCallbackImpl();
cameraKit.createCamera(cameraId, cameraStateCallback, eventHandler);
}
至此整个相机初始化过程结束。
还有一点需要补充的是,由于在前一篇文章中说明的获取权限的过程和本文中的布局初始化是异步执行的,导致布局初始化会在获取所有权限之前完成。如果在布局初始化之后紧接着初始化相机,会导致初始化过程失败。因此本文使用按钮启动相机的初始化过程。 以下是动作视频:
参考资料
相机示例代码
https://gitee.com/openharmony/app_samples/tree/master/media/Camera
权限开发概述
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/security-permissions-overview-0000000000029883
权限开发指导
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/security-permissions-guidelines-0000000000029886
应用权限列表
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/security-permissions-available-0000001051089272