I have a photo app that is using AV Foundation. I have setup a preview layer using AVCaptureVideoPreviewLayer that takes up the top half of the screen. So when the user is tryin
Here's @Erik Allen's answer in Swift 3:
let originalSize: CGSize
let visibleLayerFrame = self?.photoView.bounds
// Calculate the fractional size that is shown in the preview
let metaRect = (self?.videoPreviewLayer?.metadataOutputRectOfInterest(for: visibleLayerFrame ?? CGRect.zero)) ?? CGRect.zero
if (image.imageOrientation == UIImageOrientation.left || image.imageOrientation == UIImageOrientation.right) {
// For these images (which are portrait), swap the size of the
// image, because here the output image is actually rotated
// relative to what you see on screen.
originalSize = CGSize(width: image.size.height, height: image.size.width)
} else {
originalSize = image.size
}
let cropRect: CGRect = CGRect(x: metaRect.origin.x * originalSize.width, y: metaRect.origin.y * originalSize.height, width: metaRect.size.width * originalSize.width, height: metaRect.size.height * originalSize.height).integral
if let finalCgImage = image.cgImage?.cropping(to: cropRect) {
let finalImage = UIImage(cgImage: finalCgImage, scale: 1.0, orientation: image.imageOrientation)
// User your image...
}