1 首先我们需要绘制故事板中的一些控件,再关联方法,如下图:
2 代码实现:
#import "ViewController.h"
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *myImageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//相册
- (IBAction)selectImage:(id)sender {
//相册的资源访问UIImagePickerController来读取
UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
/*
UIImagePickerControllerSourceTypePhotoLibrary 相册
UIImagePickerControllerSourceTypeCamera 拍照 摄像
UIImagePickerControllerSourceTypeSavedPhotosAlbum 时刻
*/
//数据源类型
imagePickerC.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
//是否允许编辑
imagePickerC.allowsEditing = YES;
imagePickerC.delegate = self;
[self presentViewController:imagePickerC animated:YES completion:NULL];
}
//照相
- (IBAction)takePhoto:(id)sender {
/*
UIImagePickerControllerCameraDeviceRear:后置摄像头
UIImagePickerControllerCameraDeviceFront:前置摄像头
*/
//判断是否有摄像头
BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isCamera) {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"没有可用的摄像头" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertC addAction:action];
[self presentViewController:alertC animated:YES completion:NULL];
return;
}
UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
//数据源的类型
imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerC.delegate = self;
[self presentViewController:imagePickerC animated:YES completion:NULL];
}
//视频
- (IBAction)video:(id)sender {
}
//拍摄
- (IBAction)shoot:(id)sender {
}
#pragma mark - UIImagePickerController Delegate
//完成选择之后
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSLog(@"info = %@",info);
/*
UIImagePickerControllerEditedImage:编辑后的图片
UIImagePickerControllerOriginalImage:编辑前的图片
*/
UIImage *img = info[UIImagePickerControllerEditedImage];
self.myImageView.image = img;
//如果是照相
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//保存到相册中
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"取消选择");
[self dismissViewControllerAnimated:YES completion:NULL];
}
//照片保存成功的回调方法 注意:方法名命名有要求
- (void) image: (UIImage *) image
didFinishSavingWithError: (NSError *) error
contextInfo: (void *) contextInfo{
NSLog(@"保存成功");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end