UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
}];
UIAlertAction *camera = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentViewController:imagePicker animated:YEScompletion:nil];
}];
UIAlertAction *picture = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
}
pickerImage.delegate = self;
pickerImage.allowsEditing = NO;
[self presentViewController:pickerImage animated:YEScompletion:nil];
}];
[alertVc addAction:cancle];
[alertVc addAction:camera];
[alertVc addAction:picture];
[self presentViewController:alertVc animated:YES completion:nil];
// 上面写到Button的点击事件方法里,下面直接复制就OK,记得遵守代理协议
UIImagePickerControllerDelegate, UINavigationControllerDelegate
// 选择图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
//当选择的类型是图片
if ([type isEqualToString:@"public.image"])
{
//先把图片转成NSData
UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *data;
if (UIImagePNGRepresentation(image) ==nil)
{
data = UIImageJPEGRepresentation(image,1.0);
}
else
{
data = UIImagePNGRepresentation(image);
}
//图片保存的路径
//这里将图片放在沙盒的documents文件夹中
NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//把刚刚图片转换的data对象拷贝至沙盒中并保存为image.png
[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/userHeader.png"] contents:data attributes:nil];
//关闭相册界面
[picker dismissViewControllerAnimated:YEScompletion:nil];
//加在视图中
[self.mineView.headerButton setBackgroundImage:image forState:(UIControlStateNormal)];
}
}
// 取消选取图片
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YEScompletion:nil];
}