The camera framework offers capabilities for focusing, enabling applications to configure focus modes and focus points based on specific use cases.
For details about the APIs, see Camera API Reference.
Import the NDK APIs.
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit'; Call isFocusModeSupported to check whether the device supports a focus mode.
This operation must be performed after the session calls commitConfig to complete stream configuration.
function isFocusModeSupported(photoSession: camera.PhotoSession): boolean {
let status: boolean = false;
try {
// Check whether the autofocus mode is supported.
status = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO);
} catch (error) {
// If the operation fails, error.code is returned and processed.
let err = error as BusinessError;
console.error(`The isFocusModeSupported call failed. error code: ${err.code}`);
}
return status;
} Call setFocusMode to set the focus mode.
If autofocus is used, you can call setFocusPoint to set the focus point. The camera triggers autofocus based on the focus point.
This operation must be performed after the session calls commitConfig to complete stream configuration.
function setFocusMode(photoSession: camera.PhotoSession): void {
const focusPoint: camera.Point = {x: 1, y: 1};
try {
// Set the autofocus mode.
photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO);
// Set the focus point.
photoSession.setFocusPoint(focusPoint);
} catch (error) {
// If the operation fails, error.code is returned and processed.
let err = error as BusinessError;
console.error(`The setFocusMode and setFocusPoint call failed. error code: ${err.code}`);
}
} During camera application development, you can listen for camera focus status changes at any time.
Obtain the listening result by registering the callback function of focusStateChange. This event is triggered only when the camera focus status changes in autofocus mode.
function onFocusStateChange(photoSession: camera.PhotoSession): void {
photoSession.on('focusStateChange', (err: BusinessError, focusState: camera.FocusState) => {
if (err !== undefined && err.code !== 0) {
console.error(`focusStateChange error code: ${err.code}`);
return;
}
console.info(`focusStateChange focusState: ${focusState}`);
// To ensure user experience of the focus function, you can set the focus mode to continuous autofocus after autofocus is successful, meeting the focus requirement in a complex photographing scenario.
if (focusState === camera.FocusState.FOCUS_STATE_FOCUSED) {
photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
}
});
}