之前自己写了一个扫描二维码Demo,本来在iPhone上跑,最近用iPad也跑一下,发现了一点问题,毕竟自己没开发过iPad App,经过一番折腾,发现了原来摄像头的方向和屏幕的方向是分开的。
iPad上的方向配置
一般情况下,我们会在项目配置里勾选支持的方向,但是如果选择了Universal
,就要留意一下info.plist
文件里的配置,iPhone
和 iPad
是分开配置的
摄像头方向
由于自己不熟悉iPad配置,而且我的iPad锁定了横屏,导致我的扫描二维码Demo里摄像头方向不对,这时候我才发现,原来屏幕方向和摄像头方向其实是分开的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init]; self.session = captureSession;
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
[captureSession addInput:inputDevice];
AVCaptureMetadataOutput *captureOutput = [[AVCaptureMetadataOutput alloc] init]; [captureOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; [captureSession addOutput:captureOutput]; [captureOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession]; self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; self.previewLayer.frame = self.view.bounds; [self.view.layer addSublayer:self.previewLayer];
|
弄好扫描代码后,就可以设置摄像头方向了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
AVCaptureConnection *previewLayerConnection = self.previewLayer.connection;
UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;
if ([previewLayerConnection isVideoOrientationSupported]) { switch (interfaceOrientation) { case UIInterfaceOrientationPortrait: [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; break; case UIInterfaceOrientationLandscapeRight: [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight]; break; case UIInterfaceOrientationLandscapeLeft: [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft]; break; default: [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; break; } }
|
经过一番配置,摄像头的方向终于和屏幕方向一致了。
参考
iphone - iOS: camera orientation - Stack Overflow
iOS 获取屏幕方向,和强制屏幕旋转