點(diǎn)擊圖片調(diào)取相機(jī)或相冊(cè)
//遵循協(xié)議(調(diào)取相冊(cè)、相機(jī)使用)
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//給頭像開啟用戶交互
self.avatarImage.userInteractionEnabled = YES;
//設(shè)置手勢(shì)識(shí)別
UITapGestureRecognizer * recognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addDevies)];
[self.avatarImage addGestureRecognizer:recognize];
//圖片點(diǎn)擊事件
- (void)addDevies
{
//創(chuàng)建UIAlertController是為了讓用戶去選擇照片來(lái)源,拍照或者相冊(cè).
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:0];
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.allowsEditing = YES;
//相冊(cè)
UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"從相冊(cè)選取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:imagePickerController animated:YES completion:^{}];
}];
//相機(jī)
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePickerController animated:YES completion:^{}];
}];
//取消
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action)
{
//這里可以不寫代碼
}];
[self presentViewController:alertController animated:YES completion:nil];
//用來(lái)判斷來(lái)源 Xcode中的模擬器是沒(méi)有拍攝功能的,當(dāng)用模擬器的時(shí)候我們不需要把拍照功能加速
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[alertController addAction:albumAction];
[alertController addAction:cancelAction];
[alertController addAction:photoAction];
}
else
{
[alertController addAction:albumAction];
[alertController addAction:cancelAction];
[alertController addAction:photoAction];
}
}
選取完照片后要執(zhí)行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:^{}];
//選取裁剪后的圖片
UIImage image = [info objectForKey:UIImagePickerControllerEditedImage];
/ 此處info 有六個(gè)值- UIImagePickerControllerMediaType; // an NSString UTTypeImage)
- UIImagePickerControllerOriginalImage; // a UIImage 原始圖片
- UIImagePickerControllerEditedImage; // a UIImage 裁剪后圖片
- UIImagePickerControllerCropRect; // an NSValue (CGRect)
- UIImagePickerControllerMediaURL; // an NSURL
- UIImagePickerControllerReferenceURL // an NSURL that references an asset in the AssetsLibrary framework
- UIImagePickerControllerMediaMetadata // an NSDictionary containing metadata from a captured photo
*/
_avatarImage.image = image;
}