照相/图片库

本文介绍如何在iOS应用中使用UIImagePickerController来实现拍照和从相册选择图片的功能。通过展示具体的代码示例,包括弹出UIAlertController供用户选择操作方式,并实现UIImagePickerControllerDelegate方法来处理用户的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UIImagePickerController是图片控制器,需要继承UIImagePickerControllerDelegate,UINavigationControllerDelegate代理

点击拍照按钮,模态弹出UIAlertController控制器类,代码如下:

- (void)onCamera
{
    //常用控件
    //UIAlertView 警告视图 (iOS 8.0以前)
    //UIActionSheet        (iOS 8.0以前)

    //UIAlertController    (iOS 8.0以后)
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    //添加第一个Action,从图片库选择照片
    [ac addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self loadImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];

    //添加第二个Action,拍照
    [ac addAction:[UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self loadImagePicker:UIImagePickerControllerSourceTypeCamera];
    }]];

    //添加第三个Action,取消
    [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

    }]];

    //显示页面
    [self presentViewController:ac animated:YES completion:nil];

}

弹出图片控制器

- (void)loadImagePicker:(UIImagePickerControllerSourceType)type
{
    //首先,判断soureType 是否可用
    if ([UIImagePickerController isSourceTypeAvailable:type]) {
        //创建UIImagePickerController对象
        UIImagePickerController *pickerContr = [[UIImagePickerController alloc] init];

        //设置属性
        pickerContr.sourceType = type;
        //设置代理
        pickerContr.delegate = self;

        //显示imagePicker控制器
        [self presentViewController:pickerContr animated:YES completion:nil];
    }else {
        NSLog(@"source type is not available , type = %ld",type);
    }
}

两个代理方法

#pragma mark - 代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //返回上一个页面,关闭当前页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //info 存储选择的图片
    UIImage *img = info[UIImagePickerControllerOriginalImage];

    self.iv.image = img;

    //关闭页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值