Overview
The DataCaptureView
does not support adding a pre-built CameraSwitchControl
on React Native like other supported platforms or frameworks. However, it can be implemented with a custom button and added logic.
âšī¸ See all the supported features by the framework in the table below. |
Â
How to Create a Custom CameraSwitchControl
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
interface CameraSwitchButtonProps {
onPress: () => void;
}
export const CameraSwitchButton: React.FC<CameraSwitchButtonProps> = ({
onPress
}) => {
return (
<TouchableOpacity
style={styles.switchCameraButton}
onPress={onPress}
>
<Text style={styles.switchCameraButtonText}>đ</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
switchCameraButton: {
position: 'absolute',
top: 40,
right: 20,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
borderRadius: 5,
padding: 10,
zIndex: 10,
},
switchCameraButtonText: {
color: 'white',
fontSize: 20,
},
});
How to Use the Custom CameraSwitchControl
export const App = () => {
const cameraSettingsRef = useRef<CameraSettings>((() => {
const settings = new CameraSettings();
settings.preferredResolution = VideoResolution.FullHD;
return settings;
})());
...
const handleSwitchCamera = async () => {
if (!camera) return;
cameraPositionRef.current = (cameraPositionRef.current === CameraPosition.WorldFacing)
? CameraPosition.UserFacing
: CameraPosition.WorldFacing;
const newCamera = Camera.asPositionWithSettings(
cameraPositionRef.current,
cameraSettingsRef.current
);
if (!newCamera) return;
await camera.switchToDesiredState(FrameSourceState.Off);
await dataCaptureContext.setFrameSource(null);
await dataCaptureContext.setFrameSource(newCamera);
setCamera(newCamera);
await newCamera.switchToDesiredState(FrameSourceState.On);
};
...
return (
<View style={styles.container}>
<DataCaptureView
style={styles.dataCaptureView}
context={dataCaptureContext}
ref={viewRef}
/>
<CameraSwitchButton onPress={handleSwitchCamera} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
dataCaptureView: {
flex: 1,
},
});