Skip to content

Instantly share code, notes, and snippets.

@StanDimitroff
Created February 16, 2018 10:16
Show Gist options
  • Save StanDimitroff/e30f1bb9e3265103108db73052487ed9 to your computer and use it in GitHub Desktop.
Save StanDimitroff/e30f1bb9e3265103108db73052487ed9 to your computer and use it in GitHub Desktop.
Image cropping to AVCaptureVideoPreviewLayer rect
extension UIImage {
func crop(toPreviewLayer layer: AVCaptureVideoPreviewLayer, withRect rect: CGRect) -> UIImage {
let outputRect = layer.metadataOutputRectConverted(fromLayerRect: rect)
var cgImage = self.cgImage!
let width = CGFloat(cgImage.width)
let height = CGFloat(cgImage.height)
let cropRect = CGRect(
x: outputRect.origin.x * width,
y: outputRect.origin.y * height,
width: outputRect.size.width * width,
height: outputRect.size.height * height)
cgImage = cgImage.cropping(to: cropRect)!
let croppedUIImage = UIImage(
cgImage: cgImage,
scale: self.scale,
orientation: self.imageOrientation
)
return croppedUIImage
}
}
@undeadlegion
Copy link

Just what I was looking for, thanks!

@cristea2017
Copy link

same for me

Just what I was looking for, thanks!

same for me +100 to his karma :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment