- (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開發圖片的基本選取
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.