从摄像头获取照片和视频
-
UIImagePickerController
-
可通过
UIImagePickerController
获取视频- 录制长达30min的视频
- 将视频文件路径以
NSString
形式传递给应用程序
-
可设置使用前置或后置摄像头,是否使用LED灯,是否允许用户裁剪或调整照片或视频
-
工作方式:
- 创建实例
- 根据需要配置选取器
- 选取器包含一个符合
UIImagePickerControllerDelegate
协议的委托对象 - 当前的视图控制器通常会调用
presentViewController:animated:completion:
,所以视图控制器呈现为模态 - 用户完成照片或视频后,委托对象接收
imagePickerController:didFinishPickingMediaWithInfo:
消息- 后者接收一个字典,包含用户获取的媒体信息
- 原始或编辑过的照片
- 视频文件位置
- 或其他有用信息
- 需调用
dismissViewControllerAnimated:completion:
释放图片选取器
- 后者接收一个字典,包含用户获取的媒体信息
- 用户选择取消图片选择器,委托对象接收
imagePickerControllerDidCancel:
- 需调用
dismissViewControllerAnimated:completion:
释放图片选取器,否则,取消按钮不会起任何作用
- 需调用
-
判断有哪些摄像头可用
+ isSourceTypeAvailable:
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //摄像头存在至少一个摄像头 }else { //摄像头不可用 }
-
判断前置或后置摄像头是否可用
+ isCameraDeviceAvailable:
if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllercameraDeviceFront]) { //前置摄像头可用 } if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) { //后置摄像头可用 }
-
拍照实例部分代码
- (IBAction)takePhoto:(id)sender { UIImagePickerController *pickerController = [[UIImagePickerController alloc]init]; if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //设置视图控制器控制摄像头 pickerController.sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) { pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront; }else{ pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear; } pickerController.delegate = self; //将当前的视图控制器拿掉 [self presentViewController:pickerController animated:YES completion:nil]; } } //视图控制器的UIImagePickerControllerDelegate方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; self.imageView.image = image; [picker dismissViewControllerAnimated:YES completion:nil]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; }
网友评论