OpenCv iOS camera preview single orientation only without stretching
<p>I'm writing a OpenCv Cordova plugin for iOS. I needed the camera preview to be fullscreen and to maintain aspect ratio for all iOS devices (iPhone, iPads).</p>

<p>I was able to achieve Portrait mode (see code) and it works perfectly on iPhone 6/plus but the camera preview is stretched slightly on iPads possibly due to the fact that <strong>AVCaptureSessionPresetHigh's</strong> supported resolution is 1280x720. Anyone has any ideas on how to achieve single orientation (landscape or portrait only) and maintain aspect ratio?</p>

<p>My current code for starting a camera is </p>

<pre><code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // Initialize imageView to fullscreen
    imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:imageView];
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    [imageView setClipsToBounds:YES];

    self.videoCamera = [[FixedCvVideoCamera alloc] initWithParentView:imageView];
    self.videoCamera.delegate = self;
    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPresetHigh;
    self.videoCamera.defaultAVCaptureVideoOrientation =  AVCaptureVideoOrientationPortrait;
    self.videoCamera.defaultFPS = 30;
    [self.videoCamera start];
}
</code></pre>

<p>Notice I'm using <strong>FixedCvVideoCamera</strong> instead of the OpenCv CvVideoCamera class. The reason is that I'm subclassing and overriding CvVideoCamera's <strong>layoutPreviewLayer</strong> function to keep portrait mode.</p>

<pre><code> - (void)layoutPreviewLayer;
{
    if (self.parentView != nil)
    {
        CALayer* layer = self-&gt;customPreviewLayer;
        CGRect bounds = self-&gt;customPreviewLayer.bounds;
        int rotation_angle = 0;

        switch (defaultAVCaptureVideoOrientation) {
            case AVCaptureVideoOrientationLandscapeRight:
                rotation_angle = 270;
                break;
            case AVCaptureVideoOrientationPortraitUpsideDown:
                rotation_angle = 180;
                break;
            case AVCaptureVideoOrientationLandscapeLeft:
                rotation_angle = 90;
                break;
            case AVCaptureVideoOrientationPortrait:
            default:
                break;
        }

        layer.position = CGPointMake(self.parentView.frame.size.width/2., self.parentView.frame.size.height/2.);
        layer.affineTransform = CGAffineTransformMakeRotation( DEGREES_RADIANS(rotation_angle) );
        layer.bounds = bounds;
    }
}
</code></pre>

<p>Thanks in advance.</p>