调用手机相册换图片
文章目录
- 调用手机相册换图片
- 之前的更换头像:
- 1.首先,调用手机相册首先要在info.plist中加入字段:
- 2.然后在viewController里添加头文件:
- 3.创建UIImagePickerController的属性并完成初始化
- 4.因此我们设定一个button点击来更换图片
- 5.用警告指示器来选择相机还是相册:
- 6.因为虚拟机没有相机,所以只能调用相册:
- 7.将相册中的元素,通过协议函数赋值:
之前在暑假写的项目里,有过换图片的部分,但是当时的图片是用一个界面写好放在里面,点击图片,将图片传值到另一个界面即可。但在更多时候我们手机上的app换头像,是从手机相册调取图片去更改图片,对于这个给如何做呢?
之前的更换头像:
1.首先,调用手机相册首先要在info.plist中加入字段:
2.然后在viewController里添加头文件:
// 系统相机
#import <AVFoundation/AVFoundation.h>
// 系统相册
#import <AssetsLibrary/AssetsLibrary.h>
3.创建UIImagePickerController的属性并完成初始化
@property (nonatomic, strong) UIImagePickerController *imagePicker;
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.editing = YES;
self.imagePicker.delegate = self;
//是否允许编辑
self.imagePicker.allowsEditing = YES;
self.imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
需要注意的是:
UIImagePickerController是UINavigationController的子类
然后UINavigationController又是UIViewController的子类
所以UIImagePickerController也是一个视图控制器,不能直接在viewDilLoad里面弹出,否则会程序崩溃。
同理,也需要遵守两个协议:
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
4.因此我们设定一个button点击来更换图片
点击button:
- (void)press {
//创建sheet提示框,提示选择相机还是相册
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择照片来源" message:@"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//选择相机时,设置UIImagePickerController对象相关属性
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//self.imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
//跳转到UIImagePickerController控制器弹出相机
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
//相册选项
UIAlertAction *photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//选择相册时,设置UIImagePickerController对象相关属性
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//跳转到UIImagePickerController控制器弹出相册
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
//取消按钮
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
//添加各个按钮事件
[alert addAction:camera];
[alert addAction:photo];
[alert addAction:cancel];
//弹出sheet提示框
[self presentViewController:alert animated:YES completion:nil];
}
5.用警告指示器来选择相机还是相册:
6.因为虚拟机没有相机,所以只能调用相册:
7.将相册中的元素,通过协议函数赋值:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
-
[picker dismissViewControllerAnimated:YES completion:nil];
//获取到的图片
UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage];
self.imageView.image = image;
}