- (IBAction)selectPhoto:(id)sender
{
UIActionSheet *_sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"打开照相机", @"从相册中获取", nil];
[_sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
//选择照相机
[self takePhoto];
break;
case 1:
//选择相册
[self LocalPhoto];
break;
default:
break;
}
}
- (void)takePhoto
{
UIImagePickerControllerSourceType sourcType = UIImagePickerControllerSourceTypeCamera;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.sourceType = sourcType;
[self presentViewController:picker animated:YES completion:^{
}];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无法调取相机,请检查" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
return;
}
}
- (void)LocalPhoto
{
// 1. 实例化照片选择控制器
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
// 2. 设置照片源
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// 3. 设置是否允许编辑
[imagePicker setAllowsEditing:YES];
// 4. 设置代理
[imagePicker setDelegate:self];
// 5. 显示照片选择控制器
[self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - 照片选择代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 1. 获取编辑后的照片
UIImage *image;
switch (picker.sourceType) {
case UIImagePickerControllerSourceTypeCamera:
image = info[@"UIImagePickerControllerOriginalImage"];
//将图片保存到相册
[self saveImageToPhotos:image];
break;
case UIImagePickerControllerSourceTypePhotoLibrary:
image = info[@"UIImagePickerControllerEditedImage"];
break;
default:
break;
}
// 2. 设置按钮的图像
[_photoButton setImage:image forState:UIControlStateNormal];
// 3. 关闭照片选择控制器
[self dismissViewControllerAnimated:YES completion:nil];
}
//将图片保存到相册
- (void)saveImageToPhotos:(UIImage*)savedImage
{
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *msg = nil ;
if(error != NULL){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
iOS开发图片的基本选取
最新推荐文章于 2024-05-11 09:44:32 发布