美文网首页iOS开发技巧
UIImagePickerController

UIImagePickerController

作者: dididududididu | 来源:发表于2016-04-06 09:03 被阅读532次

    iOS 获取图片有三种方法:
    1. 直接调用摄像头拍照
    2. 从相册中选择
    3. 从图库中选择

    UIImagePickerController 是系统提供的用来获取图片和视频的接口;
    UIImagePickerController 类来获取图片视频,大体分为以下几个步骤:
    1. 初始化UIImagePickerController 类;
    2. 设置UIImagePickerController 实例的数据来源类型(下面解释);
    3. 设置设置代理;
    4. 如果需要做图片修改的话设置allowsEditing =yes。

    数据来源类型一共有三种:

    enum {
    UIImagePickerControllerSourceTypePhotoLibrary ,//来自图库
    UIImagePickerControllerSourceTypeCamera ,//来自相机
    UIImagePickerControllerSourceTypeSavedPhotosAlbum //来自相册
    };

    
    - 获取图片首先签订两个协议
    

    @interface MainViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>```

    • 在点击方法内模态推出UIImagePickerController
      • 从相册选取(需给用户选择哪种方式获取图片)
     //sourceType 是用来确认用户界面样式,选择相册
     UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
     //设置代理
     imagePicker.delegate = self;
     //允许编辑弹框
     imagePicker.allowsEditing = YES;
    //是用手机相册来获取图片的
    imagePicker.sourceType = sourceType;      
    //模态推出pickViewController
    [self presentViewController:imagePicker animated:YES completion:nil];
    
    • 从相机获取
    //sourceType 是用来确认用户界面的样式, 选择相机
     UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    //设置代理
    imagePicker.delegate = self;
    //允许编辑弹框
    imagePicker.allowsEditing = YES;
    //是用相机照相来获取图片
    imagePicker.sourceType = sourceType;
    //模态推出pickViewController
    [self presentViewController:imagePicker animated:YES completion:nil];
    
    • 实现代理方法
     //选择完图片后会回调 didFinishPickingMediaWithInfo 这个方法
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
     NSLog(@"info = %@",info);
    //隐藏控制器
        [picker dismissViewControllerAnimated:YES completion:nil];
    //给imageView 赋值图片
        imageView.image = [infoobjectForKey:UIImagePickerControllerEditedImage];
    }
    //导航条上面的 Cancel 的点击方法
    -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
      //隐藏控制器
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    

    相关文章

      网友评论

      • 超_iOS:用iPad选择相册照片后照片会被剪切成只剩下左上角.有没有遇到过?
        dididududididu:没试过iPad...

      本文标题:UIImagePickerController

      本文链接:https://www.haomeiwen.com/subject/tfgplttx.html