项目开发中经常遇到采集人脸照片的需求,需要调用相机的自拍功能。自拍后会发现照片是镜面翻转的,而项目要求使用原图,解决办法如下:
@interface ViewController()<UIImagePickerControllerDelegate> @property (nonatomic,strong) UIImagePickerController *picker; @end - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageTaken) name:@"_UIImagePickerControllerUserDidCaptureItem" object:nil]; //监听拍照完成的动作 } //拍照 - (void)takePhoto { _picker = [[UIImagePickerController alloc]init]; _picker.sourceType = UIImagePickerControllerSourceTypeCamera; _picker.cameraDevice = UIImagePickerControllerCameraDeviceFront; //自拍 _picker.delegate = self; [self presentViewController:_picker animated:YES completion:nil]; } #pragma mark - UIImagePickerControllerDelegate -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; UIImage* flippedImage = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationLeftMirrored]; //镜面翻转图片 } - (void)imageTaken { if (_picker.cameraDevice == UIImagePickerControllerCameraDeviceFront) { //如果是自拍则翻转预览图 NSMutableArray *subviews = [NSMutableArray arrayWithObject:_picker.view]; while ([subviews count] != 0) { UIView *subview = [subviews firstObject]; [subviews removeObjectAtIndex:0]; [subviews addObjectsFromArray:subview.subviews]; if ([subview isKindOfClass:[UIImageView class]]) { subview.transform = CGAffineTransformScale(_picker.cameraViewTransform, -1, 1); } } } }