点击图片调取相机或相册
//遵循协议(调取相册、相机使用)
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//给头像开启用户交互
self.avatarImage.userInteractionEnabled = YES;
//设置手势识别
UITapGestureRecognizer * recognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addDevies)];
[self.avatarImage addGestureRecognizer:recognize];
//图片点击事件
- (void)addDevies
{
//创建UIAlertController是为了让用户去选择照片来源,拍照或者相册.
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:0];
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.allowsEditing = YES;
//相册
UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:imagePickerController animated:YES completion:^{}];
}];
//相机
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];
//用来判断来源 Xcode中的模拟器是没有拍摄功能的,当用模拟器的时候我们不需要把拍照功能加速
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[alertController addAction:albumAction];
[alertController addAction:cancelAction];
[alertController addAction:photoAction];
}
else
{
[alertController addAction:albumAction];
[alertController addAction:cancelAction];
[alertController addAction:photoAction];
}
}
选取完照片后要执行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:^{}];
//选取裁剪后的图片
UIImage image = [info objectForKey:UIImagePickerControllerEditedImage];
/ 此处info 有六个值- 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;
}
网友评论