用UIImagePickerController创建一个对象,
//设置代理
imgPickerCtrl.delegate =
self;
1.获取本地相册图片
//设置资源类型
imgPickerCtrl.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//弹出模态
imgPickerCtrl.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//弹出模态
[self
presentViewController:imgPickerCtrl
animated:YES
completion:nil];
点击”获取本地相册图片”,效果图:
//获取摄像头图片
判断摄像头的类型:前置/后置,有/无
BOOL
isAvailable = [UIImagePickerController
isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isAvailable) {
//如果没有摄像头,弹出框提示
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有可用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
return;
}
if (!isAvailable) {
//如果没有摄像头,弹出框提示
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有可用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
return;
}
//如果有,就启用摄像头拍照
imgPickerCtrl.sourceType
=
UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imgPickerCtrl animated:YES completion:nil];
[self presentViewController:imgPickerCtrl animated:YES completion:nil];
/**
* 获取本地视频
* 获取本地视频
*/
imgPickerCtrl.sourceType
=
UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//指定媒体类型,比如public.movie
imgPickerCtrl.mediaTypes =
@[@"public.movie"];
[self
presentViewController:imgPickerCtrl
animated:YES
completion:nil];
/**
* 获取摄像头视频
* 获取摄像头视频
*/
imgPickerCtrl.sourceType
=
UIImagePickerControllerSourceTypeCamera;
//指定媒体类型
imgPickerCtrl.mediaTypes = @[@"public.movie"];
[self presentViewController:imgPickerCtrl animated:YES completion:nil];
//指定媒体类型
imgPickerCtrl.mediaTypes = @[@"public.movie"];
[self presentViewController:imgPickerCtrl animated:YES completion:nil];
通过
UIImagePickerController的选中方法didFinishPickingMediaWithInfo:判断选中的是那个按钮以做出相应操作;
//取得mediaType,判断是图片还是视频
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
//如果是图片
if ([mediaType
isEqualToString:@"public.image"]) {
//获取选中的图片
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
_imgView.image = img;
//如果是摄像头拍摄的则保存到本地
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//将图片写到本地
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
}else if ([mediaType isEqualToString:@"public.movie"]){//视频
//获取视图的url
NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
//播放器播放(还没学)
}
//关闭当前的模态视图
[self dismissViewControllerAnimated:YES completion:nil];
保存摄像头图片后还可以用
didFinishSavingWithError:方法进行操作,比如用弹出框提示@“保存成功"