在iOS中要拍照和录制视频最简单的方式就是调用UIImagePickerController
- UIImagePickerController继承与UINavigationController,需要使用代理方法时需要同时遵守这两个协议
- 使用UIImagePickerController来选择相册图片或者拍摄图片,其实它的功能还能用来拍摄视频。
代码
//更换头像方法
- (void)changeHeaderImage
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
imagePickerController.allowsEditing = YES;
UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self selectImageFromCamera:imagePickerController];
}];
UIAlertAction * defaultAction1 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self selectImageFromAlbum:imagePickerController];
}];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:defaultAction];
[alert addAction:cancelAction];
[alert addAction:defaultAction1];
[self presentViewController:alert animated:YES completion:nil];
}
//调用相机
-(void)selectImageFromCamera:(UIImagePickerController *)imagePickerVC
{
imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
//相机类型(拍照、录像...)字符串需要做相应的类型转换
imagePickerVC.mediaTypes = @[(NSString *)kUTTypeImage];
//设置摄像头模式(拍照,录制视频)
imagePickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
//调用系统相册
-(void)selectImageFromAlbum:(UIImagePickerController *)imagePickerVC
{
imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//判断资源类型
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//如果是图片
UIImage *image = info[UIImagePickerControllerEditedImage];
[self saveImage:image withName:headerImageName];
NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:0];
[_backTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
// 保存图片至沙盒(应该是提交后再保存到沙盒,下次直接去沙盒取)
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
// 获取沙盒目录
NSString *headImagePath = [kPathDocument stringByAppendingPathComponent:imageName];
// 将图片写入文件
[imageData writeToFile:headImagePath atomically:NO];
}