Finally, I found the following to work best for my application. In my application, I now add the ViewFinderViewController as a child view controller:
- (void)viewWillAppear:(BOOL)animated; { if ([self.childViewControllers containsObject:self.viewfinderViewController] == NO) { [self addChildViewController:self.viewfinderViewController]; self.viewfinderViewController.view.frame = self.view.bounds; [self.view addSubview:self.viewfinderViewController.view]; [self.viewfinderViewController didMoveToParentViewController:self]; } }
Thus, the willAnimateRotationToInterfaceOrientation: method will be called automatically, which I previously redirected from the view controller, which added the viewfinder view when it is being watched.
In addition, I update the preview size in this ViewfinderViewController method:
- (void)viewWillLayoutSubviews; { self.previewLayer.frame = self.view.bounds; }
I handle the previewLayer rotation by implementing these two methods:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [CATransaction begin]; [CATransaction setAnimationDuration:duration]; [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; [self updatePreviewLayerForOrientation:toInterfaceOrientation]; [CATransaction commit]; } - (void)updatePreviewLayerForOrientation:(UIInterfaceOrientation)interfaceOrientation; { // correct position of previewLayer CGSize newSize = self.view.bounds.size; self.previewLayer.position = CGPointMake(0.5 * newSize.width, 0.5 * newSize.height); // rotate the previewLayer, in order to have camera picture right switch (interfaceOrientation) { case UIInterfaceOrientationPortrait: [self.previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)]; break; case UIInterfaceOrientationLandscapeLeft: [self.previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)]; break; case UIInterfaceOrientationLandscapeRight: [self.previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)]; break; case UIDeviceOrientationPortraitUpsideDown: [self.previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)]; break; default: break; } }
Hope this helps everyone who adds AVCaptureVideoPreviewLayer as a sublevel and has problems with resizing and orientation when it comes to rotating the interface.
source share