项目场景:
使用react-native-image-crop-picker
第三方库,实现头像上传功能。
iOS/Android 图像选择器,支持相机、视频、可配置压缩、多图像和裁剪。
如何使用:
1、添加依赖
yarn add react-native-image-crop-picker
cd ios
pod install
2、在 Xcode 中打开 Info.plist ,添加字符串键Privacy - Camera Usage Description
,Privacy - Photo Library Usage Description
和Privacy - Microphone Usage Description
键,并设置value值。
3、简单使用
/*
* @Date: 2024-08-02 10:42:19
* @LastEditors: mina
* @LastEditTime: 2024-08-02 16:49:23
* @Description: https://github.com/ivpusic/react-native-image-crop-picker
*/
import React, { useState } from 'react'
import { View, Button, Image, StyleSheet, Alert, Linking, Platform } from 'react-native'
import ImagePicker from 'react-native-image-crop-picker'
import { useActionSheet } from '@expo/react-native-action-sheet'
const AvatarPicker = () => {
const [avatar, setAvatar] = useState(null)
const { showActionSheetWithOptions } = useActionSheet()
const handlePermissionDenied = () => {
showActionSheetWithOptions(
{
options: ['Open Settings', 'Cancel'],
cancelButtonIndex: 1,
title: 'Permission Required',
message: 'Please enable camera and photo library permissions in the app settings.',
},
(buttonIndex) => {
if (buttonIndex === 0) {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:')
} else {
Linking.openSettings()
}
}
},
)
}
const handleActionSheetPress = (index) => {
if (index === 0) {
ImagePicker.openCamera({
width: 100,
height: 100,
cropping: true,
compressImageMaxWidth: 100,
compressImageMaxHeight: 100,
compressImageQuality: 0.7,
mediaType: 'photo',
includeBase64: true,
})
.then((image) => {
setAvatar({ uri: image.path, base64: image.data })
})
.catch((error) => {
if (error.code === 'E_NO_CAMERA_PERMISSION') {
handlePermissionDenied()
} else {
console.log('Error taking photo: ', error)
}
})
} else if (index === 1) {
ImagePicker.openPicker({
width: 100,
height: 100,
cropping: true,
compressImageMaxWidth: 100,
compressImageMaxHeight: 100,
compressImageQuality: 0.7,
mediaType: 'photo',
includeBase64: true,
})
.then((image) => {
setAvatar({ uri: image.path, base64: image.data })
})
.catch((error) => {
console.log('error.code', error.code)
if (error.code === 'E_NO_LIBRARY_PERMISSION') {
handlePermissionDenied()
} else {
console.log('Error picking image: ', error)
}
})
}
}
const showActionSheet = () => {
const options = ['Take photos', 'Select from album', 'Cancel']
const cancelButtonIndex = 2
showActionSheetWithOptions(
{
options,
cancelButtonIndex,
},
handleActionSheetPress,
)
}
return (
<View style={styles.container}>
<Button title="Pick an Avatar" onPress={showActionSheet} />
{avatar && <Image source={{ uri: avatar.uri }} style={styles.avatar} />}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
avatar: {
width: 100,
height: 100,
borderRadius: 20,
marginTop: 20,
},
})
export default AvatarPicker
/* use example
<AvatarPicker></AvatarPicker>
*/