React Native學習-調取攝像頭第三方組件:react-native-image-picker


近期做的軟件中圖片處理是重點,那么自然也就用到了相機照相或者相冊選取照片的功能。

react-native中有image-picker這個第三方組件,但是0.18.10這個版本還不是太支持iPad。

這個組件同時支持photo和video,也就是照片和視頻都可以用這個組件實現。

安裝

 npm install --save react-native-image-picker

安裝過之后要執行rnpm link命令

用法

 import ImagePickerManager from 'NativeModules';
 
 當你想展示相機還是相冊這個選擇器時:(變量options還有其它的設置,一些使用它的默認值就可以滿足我們的要求,以下是我使用到的)
var options = {
  title: 'Select Avatar', // 選擇器的標題,可以設置為空來不顯示標題
  cancelButtonTitle: 'Cancel',
  takePhotoButtonTitle: 'Take Photo...', // 調取攝像頭的按鈕,可以設置為空使用戶不可選擇拍照
  chooseFromLibraryButtonTitle: 'Choose from Library...', // 調取相冊的按鈕,可以設置為空使用戶不可選擇相冊照片
  customButtons: {
    'Choose Photo from Facebook': 'fb', // [按鈕文字] : [當選擇這個按鈕時返回的字符串]
  },
  mediaType: 'photo', // 'photo' or 'video'
  videoQuality: 'high', // 'low', 'medium', or 'high'
  durationLimit: 10, // video recording max time in seconds
  maxWidth: 100, // photos only默認為手機屏幕的寬,高與寬一樣,為正方形照片
  maxHeight: 100, // photos only
  allowsEditing: false, // 當用戶選擇過照片之后是否允許再次編輯圖片
};
 
ImagePickerManager.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (response.error) {
    console.log('ImagePickerManager Error: ', response.error);
  }
  else if (response.customButton) {
    // 這是當用戶選擇customButtons自定義的按鈕時,才執行
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    // You can display the image using either data:

    if (Platform.OS === 'android') {
        source = {uri: response.uri, isStatic: true};
    } else {
        source = {
            uri: response.uri.replace('file://', ''),
            isStatic: true
        };
    }

    this.setState({
      avatarSource: source
    });
  }
});

 

顯示圖片的方法:
<Image source={this.state.avatarSource} style={styles.uploadAvatar} />

當然我們也有不想讓用戶選擇的時候,而是直接就調用相機或者相冊,這個組件中還有其它的函數:

// Launch Camera:
  ImagePickerManager.ImagePickerManager.launchCamera(options, (response)  => {
    // Same code as in above section!
  });

  // Open Image Library:
  ImagePickerManager.ImagePickerManager.launchImageLibrary(options, (response)  => {
    // Same code as in above section!
  });

 

更詳細的可以查看它的官網:https://github.com/marcshilling/react-native-image-picker

這個組件只支持從相冊中選取一張圖片,如果滿足不了需求,可以先學習了解一下官方版react-native的demo:里邊有CameraRoll可以支持從相冊中獲取多張圖片。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM