免费开源的iOS开发学习平台

相机与相册的调用:2-UIImagePickerController的使用

本节我们创建一个应用,使用UIImagePickerController允许用户通过相机或者图库来选取一张图像并在控制器上的UIImageView控件中显示。

准备工作

我们需要预先在Info.plist文件中,添加相机、相册的使用权限。

在Storyboard中搭建界面,添加一个UIImageView控件并与控制器建立连线,用于显示选中的图片。

在控制器中添加UIImagePickerController类型的属性,并设置控制器遵守相关的协议。

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property(nonatomic,strong)UIImagePickerController *imagePickerController;
@property (weak, nonatomic) IBOutlet UIImageView *photoImageView;
@end

初始化imagePickerController的属性

- (UIImagePickerController *)imagePickerController {
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

使用UIImagePickerController实现图片的选择功能

在viewDidAppear:方法中,添加如下代码,可以实现当控制器视图显示后,在屏幕底部显示一个提示框,用于接收用户选择图片来源。该方法中,可以判断运行应用的设备是否支持摄像头,如果在真机上运行,则可以提供从摄像头获取图片。

-(void)viewDidAppear:(BOOL)animated{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *photosAlbumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [alert addAction:cameraAction];
    }
    [alert addAction:photosAlbumAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

在UIImagePickerControllerDelegate代理协议提供的方法中,可以从info参数中获取用户选择的图片,并显示在创建的UIImageView控件上。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image  =  [info objectForKey:UIImagePickerControllerOriginalImage];
    self.photoImageView.image = image;
}

在模拟器中运行结果如下:

示例代码

https://github.com/99ios/17.4.2