Mirroring (flipping) camera preview layer
avcapturesession, camera, ios, swift
Solution
Nowadays, if you use the `mirrored` property of the preview layer directly, you will get a deprecation warning at runtime. The current way to do it is using directly the connection from the camera. You must do something like this (code below is not real code, property names probably will differ, but you get the idea)
if (cameraPreviewLayer.connection.SupportsVideoMirroring) {
cameraPreviewLayer.connection.automaticallyAdjustsVideoMirroring = false
cameraPreviewLayer.connection.videoMirrored = true
}
Problem
So I am using AVCaptureSession to take pictures with front camera. I am also creating previewLayer from this session to display current image on screen. ``` previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill ``` It all works like it should. But now I have a problem because I need to implement a button which will flip / mirror (transform) this preview layer - so users have a choice to take normal selfie picture or take mirrored one. I have already tried transforming previewLayer and it KINDA works. The problem is that if you rotate device, preview picture rotates in the other way since it is transformed. (in the default or any other camera app picture rotates with camera). Anyone has any idea how to achieve that? Mirroring preview layer: (I tried transforming layer and even view later, same result). ``` @IBAction func mirrorCamera(_ sender: AnyObject) { cameraMirrored = !cameraMirrored if cameraMirrored { // TRANSFORMING VIEW self.videoPreviewView.transform = CGAffineTransform(scaleX: -1, y: 1); // OR LAYER self.previewLayer.transform = CATransform3DMakeScale(-1, 1, 1); } else { self.videoPreviewView.transform = CGAffineTransform(scaleX: 1, y: 1); self.videoPreviewView.transform = CATransform3DMakeScale(1, 1, 1); } } ```