設置頭部代理 1.調用相機 檢測前置攝像頭是否可用 檢測後置攝像頭是否可用 調用相機 2.調用相冊 3.代理事件 4.將圖片保存到本地 ...
設置頭部代理
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
1.調用相機
檢測前置攝像頭是否可用
- (BOOL)isFrontCameraAvailable{ return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; }
檢測後置攝像頭是否可用
- (BOOL)isRearCameraAvailable{ return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]; }
調用相機
///調用相機 - (void)persentImagePicker{ if (!_imagePickerG) { ///初始化相機 _imagePickerG = [[UIImagePickerController alloc]init]; ///代理 _imagePickerG.delegate = self; } // 前面的攝像頭是否可用 if ([self isFrontCameraAvailable]) { _imagePickerG.sourceType = UIImagePickerControllerSourceTypeCamera; } // 後面的攝像頭是否可用 else if ([self isFirstResponder]){ _imagePickerG.sourceType = UIImagePickerControllerSourceTypeCamera; } else{ [SVProgressHUD showErrorWithStatus:@"沒有相機可用~"]; return; } ///允許拍照後裁剪 _imagePickerG.allowsEditing = YES; [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil]; }
2.調用相冊
///調用本地相冊 - (void)persentImagePicker{ if (!_imagePickerG) { ///初始化相機 _imagePickerG = [[UIImagePickerController alloc]init]; ///代理 _imagePickerG.delegate = self; } ///相冊 _imagePickerG.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; _imagePickerG.allowsEditing = YES; [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil]; }
3.代理事件
///取消選擇圖片(拍照) - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:nil]; }
///選擇圖片完成(從相冊或者拍照完成) - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];///原圖 //獲取修剪後的圖片 UIImage *imageUp = [info objectForKey:UIImagePickerControllerEditedImage]; }
4.將圖片保存到本地
///保存圖片到本地相冊 -(void)imageTopicSave:(UIImage *)image{ UIImageWriteToSavedPhotosAlbum(image, self, @selector(image: didFinishSavingWithError: contextInfo:), nil); } - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ if (error == nil) { } else{ ///圖片未能保存到本地 } }