本文內容概要:1.調用系統相機和相簿獲得照片
2.設定選擇或者拍照過後調用系統裁剪功能。
3.設定系統相機與相簿的語言為中文。
首先是建立了一個UIActionSheet,上面設定了相簿與相機還有取消按鈕,並在按鈕點擊事件中開啟相機與相簿。代碼:
// 底部選擇彈窗private UIActionSheet _actionSheet = null;public UIActionSheet ActionSheet { get {if (_actionSheet == null) {_actionSheet = new UIActionSheet();_actionSheet.AddButton("相簿");_actionSheet.AddButton("相機");_actionSheet.AddButton("取消");// 設定取消按鈕位置_actionSheet.CancelButtonIndex = _actionSheet.ButtonCount - 1;_actionSheet.Dismissed += async (sender, e) =>{// 相簿if (e.ButtonIndex == 0){// 設定取消選取和結束選取返回圖片的方法_imagePicker.FinishedPickingMedia += this.ImagePicker_FinishedPickerMedia;//設定選擇照片後可以裁剪_imagePicker.AllowsEditing = true;_imagePicker.Canceled += this.ImagePicker_Cancelled;// 設定映像來源為相簿_imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;// 進入照片圖庫await this.PresentViewControllerAsync(this._imagePicker, true);}// 相機else if (e.ButtonIndex == 1){// 判斷是否有硬體支援if (UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)){isCamera = true;// 設定取消選取和結束選取返回圖片的方法_imagePicker.FinishedPickingMedia += this.ImagePicker_FinishedPickerMedia;_imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;//設定拍照後可以裁剪_imagePicker.AllowsEditing = true;_imagePicker.Canceled += this.ImagePicker_Cancelled;// 開啟相機await this.PresentViewControllerAsync(this._imagePicker, true);}else {UIAlertView alertView = new UIAlertView();alertView.Title = "對不起,此裝置沒有相機功能";alertView.AddButton("知道了");alertView.Show();}}};}return _actionSheet;}}
下面是相簿與相機回調方法:
/// <summary>/// 相簿取消選擇調用後的方法/// </summary>/// <param name="sender">Sender.</param>/// <param name="e">E.</param>private async void ImagePicker_Cancelled(object sender, EventArgs e){isCamera = false;await this._imagePicker.DismissViewControllerAsync(true);}/// <summary>/// 相簿選擇後調用的方法/// </summary>/// <param name="sender">Sender.</param>/// <param name="e">E.</param>private async void ImagePicker_FinishedPickerMedia(object sender, UIImagePickerMediaPickedEventArgs e){// 擷取選擇後的映像 EditedImage是編輯後的照片 OriginalImage是原圖UIImage pickerImage = e.Info[UIImagePickerController.EditedImage] as UIImage;// 將選擇後的映像展示在映像視圖中...// 如果是相機則儲存圖片到相簿if (isCamera) { pickerImage.SaveToPhotosAlbum((s, error) =>{if (null != error) { }});}isCamera = false;// 退出照片庫應用程式await _imagePicker.DismissViewControllerAsync(true);}
這樣基本的照相與相簿就實現了,還需要注意的就是許可權問題。在info.plist檔案中添加如下許可權:
//這兩個是相機與相簿的許可權
Privacy - Camera Usage Description string 說明:app需要您的相簿許可權
Privacy - Photo Library Usage Description string 申請說明:
//下面這個是指定語言為中文的
Localization native development region string China