码迷,mamicode.com
首页 > 其他好文 > 详细

如何调用本地相册、相机

时间:2015-12-20 20:45:29      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

 
1、判断系统是否支持相机
[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]
2、创建相册视图控制器对象
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
3、设置sourceType(资源类型)
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;//相机
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//图片库
imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//保存的图片
4、设置弹出动画(可选)
imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
5、设置是否允许编辑图片
imagePickerController.allowsEditing = YES;
6、设置代理(UIImagePickerControllerDelegate)
imagePickerController.delegate = self;
7、实现代理方法:获取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     [picker dismissViewControllerAnimated:YES completion:nil];
    //获取图片
     UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
//取消点击
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}
8、保存图片到相册
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);//image:要保存的图片UImage对象,
- (void) image: (UIImage *) image
didFinishSavingWithError: (NSError *) error
   contextInfo: (void *) contextInfo{
//如果error==NULL,则表示图片保存成功
}
 
具体代码:
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10, 50, 80, 80);
    btn.backgroundColor = [UIColor redColor];
    [btn addTarget:self action:@selector(showpicker) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];   
}
-(void)showpicker{
    UIImagePickerController *imagepicker = [[UIImagePickerController alloc]init];
    imagepicker.sourceType = 2;//设置类型(0代表调用相册,1 代表弹出相机)
    imagepicker.allowsEditing = YES;//是否允许编辑,默认no,设置为yes时,点击图片会进入编辑界面(裁剪)
   
    imagepicker.delegate = self;//设置代理
    [self presentViewController:imagepicker animated:YES completion:nil];//弹出相册/相机
}
//选择图片后调用的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"%@",info);
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];//获取图片
    UIImageView *imageview = [[UIImageView alloc]initWithImage:image];
    imageview.frame = CGRectMake(40, 150, 100, 100);
    [self.view addSubview:imageview]; 
    [self dismissViewControllerAnimated:YES completion:nil];//消失imagepicker
}

如何调用本地相册、相机

标签:

原文地址:http://www.cnblogs.com/wxzboke/p/5061635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!