iOS拍摄照片

iOS拍摄照片

demo UI

添加一个UIImageView来显示图片,另外使用一个按键来进入拍照界面。

效果图如下:

enter description here

实现代码

1.设置代理,UIImagePickerController是UINavigationController的子类,所以UIImagePicker- Con-troller的委托也要遵守UINavigationControllerDelegate协议。

@interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

2.点击按键时进入拍照界面

- (IBAction)takePicture:(id)sender {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    //检查相机设备是否可用,不可用时则使用本地图片库
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    } else {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

3.在代理方法中显示拍照所得的图片

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //显示图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.imageView.image = image;
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

你可能感兴趣的:(ios)