Last active
April 14, 2021 08:16
-
-
Save eddieespinal/a7bb8a97ac3e935af1fb to your computer and use it in GitHub Desktop.
Crops a Picture from AVCaptureSession to the bounds of the AVCaptureVideoPreviewLayer (so Preview = CameraImage) - Swift Version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is the swift version of the following gist by @shexbeer https://gist.github.com/shexbeer/cb069d36ca8ec5edb515 | |
func cropCameraImage(original: UIImage, previewLayer: AVCaptureVideoPreviewLayer) -> UIImage? { | |
var image = UIImage() | |
let previewImageLayerBounds = previewLayer.bounds | |
let originalWidth = original.size.width | |
let originalHeight = original.size.height | |
let A = previewImageLayerBounds.origin | |
let B = CGPointMake(previewImageLayerBounds.size.width, previewImageLayerBounds.origin.y) | |
let D = CGPointMake(previewImageLayerBounds.size.width, previewImageLayerBounds.size.height) | |
let a = previewLayer.captureDevicePointOfInterestForPoint(A) | |
let b = previewLayer.captureDevicePointOfInterestForPoint(B) | |
let d = previewLayer.captureDevicePointOfInterestForPoint(D) | |
let posX = floor(b.x * originalHeight) | |
let posY = floor(b.y * originalWidth) | |
let width: CGFloat = d.x * originalHeight - b.x * originalHeight | |
let height: CGFloat = a.y * originalWidth - b.y * originalWidth | |
let cropRect = CGRectMake(posX, posY, width, height) | |
if let imageRef = CGImageCreateWithImageInRect(original.CGImage, cropRect) { | |
image = UIImage(CGImage: imageRef, scale: 2.5, orientation: .LeftMirrored) | |
} | |
return image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this code in my app, but the width and height are 0 (iPhone X with full screen landscape camera)
How I can fix?