iOS:颠倒背面照相机照片,正面朝上照片
问题描述:
我的iPad应用只能用于横向方向。在看过几十个堆栈的答案之后,我无法正确地拍摄照片(元数据可以纠正它,但仅在mac上有用)。当应用程序在LandscapeLeft中时,它会返回一张颠倒的照片,而在LandscapeRight中,这是正确的。iOS:颠倒背面照相机照片,正面朝上照片
据我所知,为预览图层设置VideoOrientation为预览图片提供了正确的方向。
_capturePreview = [[ISCapturePreview alloc] init];
[self addSubview:_capturePreview];
// Session
self.session = [AVCaptureSession new];
[self.session setSessionPreset:AVCaptureSessionPresetPhoto];
// Capture device
AVCaptureDevice* inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
// Device input
self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
if ([self.session canAddInput:self.deviceInput])
[self.session addInput:self.deviceInput];
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
// Preview
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[previewLayer.connection setVideoOrientation:(AVCaptureVideoOrientation)orientation];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [[self capturePreview] layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:CGRectMake(0, 0, 1024, 600)];
[rootLayer insertSublayer:previewLayer atIndex:0];
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
if ([self.session canAddOutput:stillImageOutput])
{
[stillImageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
[self.session addOutput:stillImageOutput];
[self setStillImageOutput:stillImageOutput];
}
[self.session startRunning];
并且输出代码在这里。在我的测试中设置VideoOrientation没有影响。
- (void)takePhotoButtonWasPressed:(id)sender{
[[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self capturePreview] layer] connection] videoOrientation]];
// Capture a still image.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
}];}
答
我目前还不能我自己测试的代码,但如果你设置了可用的方向(在项目设置)同时landscapeLeft和landscapeRight,iOS的可能是处理取向本身,所以尽量不要设置方向。此外,如果您在加载视图后更改设备的方向,则将使用错误的方向,因此请考虑添加观察者以检查更改。另外,苹果说你应该使用UITraitCollection
和UITraitEnvironment
而不是从iOS8开始的UIInterfaceOrientation
。
我希望这可以帮助你:)