本文内容概要: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