首先,在需要读取照片的控件的点击触发方法中写如下代码:
// 创建Alert弹窗
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更改头像" message:nil preferredStyle:UIAlertControllerStyleAlert];
// 判断是否支持相机.
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
NSLog(@"支持相机");
} else {
NSLog(@"不支持相机");
}
UIAlertAction *action = [UIAlertAction actionWithTitle:@"从相册上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 获取相册对象.
self.picker = [[[UIImagePickerController alloc] init] autorelease];
// 选择完成图片或点击取消按钮都是通过代理来操作所需的逻辑过程.
self.picker.delegate = self;
// 相册对象是否可编辑.
self.picker.allowsEditing = YES;
// 设置相册呈现的样式(枚举值).
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;// 相册获取.
// 使用模态推出相册.
[self presentViewController:self.picker animated:YES completion:nil];
}];
UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:action];
[alert addAction:actionCancel];
[self presentViewController:alert animated:YES completion:nil];
选择完照片,系统自动调用此方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
// 点击取消执行的代码.
[picker dismissViewControllerAnimated:YES completion:nil];
// 获取照片.
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
// 设置显示照片.
[self.buttonForUser setImage:image forState:UIControlStateNormal];
CGSize size = CGSizeMake(WIDTH / 5, WIDTH / 5);
// 调整image 的大小.
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
[image drawInRect:rect];
self.buttonForUser.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 保存图片到本地, 注意:上传照片到服务器使用(未实现).
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"用户头像"];
[[NSUserDefaults standardUserDefaults] synchronize];
}