在iOS中,系統提供了一個拍照視圖控制器UIImagePickerController,UIImagePickerController繼承於UIViewController,能夠直接present出來。spa
在一個按鈕事件裏調出拍照界面來
3d
- (IBAction)click:(id)sender {orm
self.controller = [[UIImagePickerController alloc]init];繼承
if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {事件
self.controller.delegate = self;圖片
self.controller.allowsEditing = YES;ip
self.controller.sourceType = UIImagePickerControllerSourceTypeCamera;//或者UIImagePickerControllerSourceTypeSavedPhotosAlbumit
self.controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;io
[self presentViewController:self.controller animated:YES completion:nil];cli
} else {
NSLog(@"camera is not avaliable.");
}
}
讓這個試圖控制器遵循UINavigationControllerDelegate, UIImagePickerControllerDelegate協議
實現UIImagePickerControllerDelegate協議裏的相應方法便可。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ;
上面的方法拍完照片和取照片都會走。
例如
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
NSLog(@"%@", info);
//不寫dismiss方法的話還在拍照界面
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (image == nil) {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
// [self dismissViewControllerAnimated:YES completion:nil];
UIImagePickerController *controller = [[UIImagePickerController alloc]init];
controller.delegate = self;
controller.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//爲何到不了照片庫啊?
[self.controller presentViewController:controller animated:YES completion:nil];
} else if (picker.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
//image指選中的圖片
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (image == nil) {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
self.imageView.image = image;
// [picker dismissViewControllerAnimated:YES completion:nil];
// [self.controller dismissViewControllerAnimated:YES completion:nil];
} else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
}
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error == nil) {
NSLog(@"save successfully");
} else {
NSLog(@"saving camera has a problem");
NSLog(@"%@", [error description]);
}
}
取消走下面方法:
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;