ReactNative+react-native-image-crop-pickerでローカル画像を表示

2022年11月22日

環境

手順

準備

  • Info.plistにPrivacy - Photo Library Usage Descriptionを追加
  • プロジェクトディレクトリでモジュールをインストール
    $ yarn add react-native-image-crop-picker または$ npm install react-native-image-crop-picker

コード

import React, { Component } from 'react'
import { View, StyleSheet, Text, TouchableOpacity, Image} from 'react-native'
import ImagePicker from 'react-native-image-crop-picker';

class ImageTestComponent extends Component {
  constructor() {
    super();
    this.state = {
      image: null,
    };
  }

  pickSingle(cropit, circular = false, mediaType) {
    ImagePicker.openPicker({
		  width: 500,
		  height: 500,
		  cropping: cropit,
		  cropperCircleOverlay: circular,
		  sortOrder: 'none',
		  compressImageMaxWidth: 1000,
		  compressImageMaxHeight: 1000,
		  compressImageQuality: 1,
		  compressVideoPreset: 'MediumQuality',
		  includeExif: true,
		  cropperStatusBarColor: 'white',
		  cropperToolbarColor: 'white',
		  cropperActiveWidgetColor: 'white',
		  cropperToolbarWidgetColor: '#3498DB',
    })
    .then((image) => {
			console.log('received image', image);
			this.setState({
			  image: {
				uri: image.path,
				width: image.width,
				height: image.height,
				mime: image.mime,
			  },
			  images: null,
			});
    })
    .catch((e) => {
			console.log(e);
			Alert.alert(e.message ? e.message : e);
		  });
  }
	
  renderImage(image) {
		return (
		  <Image
			style={{ width: 300, height: 300, resizeMode: 'contain' }}
			source={image}
		  />
		);
  }

  render() {
    const AppButton = ({ onPress, title }) => (
			<TouchableOpacity onPress={onPress} style={styles.appButtonContainer}>
			  <Text style={styles.appButtonText}>{title}</Text>
			</TouchableOpacity>
		  );
    return <View>
	     {this.state.image ? this.renderImage(this.state.image) : null}
	     <AppButton
			title="画像を選ぶ"
			onPress={() => this.pickSingle(false)}
			/>
	    </View>
  }
}

const styles = StyleSheet.create({
	wrapper: {
		flex: 1
	},
	appButtonContainer: {
		elevation: 8,
		backgroundColor: "#fff",
		borderRadius: 10,
		paddingVertical: 10,
		paddingHorizontal: 12
	},
	appButtonText: {
		fontSize: 15,
		color: "grey",
		alignSelf: "center",
		textTransform: "uppercase"
	}
})

export default ImageTestComponent

結果

  • 下記の画面は、mobile-previewerのLoginフォームを前節のImageTestComponentをインポートしている

参考

手順NoCode,Adalo,React Native

Posted by ttnt