I need to build a custom camera view similar to this: example image
I've used AVFoundation and placed an UIImageView over the AVCaptureVideoPreviewLayer and it look almost the same (although I'm not sure if this is the right way, thats way I wrote the title like this). I'm capturing the image and saving it to the gallery, but I need only the image in the rectangle in the middle.
Any suggestions how to do it?
Thanks in advance!
You need to crop the image in context of overlay imageView.Pass the captured image in below function that may help you.
func cropToBounds(image: UIImage) -> UIImage
{
let contextImage: UIImage = UIImage(cgImage: image.cgImage!)
let contextSize: CGSize = contextImage.size
let widthRatio = contextSize.height/UIScreen.main.bounds.size.width
let heightRatio = contextSize.width/UIScreen.main.bounds.size.height
let width = (self.imgOverlay?.frame.size.width)!*widthRatio
let height = (self.imgOverlay?.frame.size.height)!*heightRatio
let x = ((self.imgOverlay?.frame.origin.x)!)*widthRatio
let y = (self.imgOverlay?.frame.origin.y)!*heightRatio
let rect = CGRect(x: x, y: y, width: height, height: width)
let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}
Actually the answer from Nishant Bhindi needs some corrections. The code below will do the work:
func cropToBounds(image: UIImage) -> UIImage
{
let contextImage: UIImage = UIImage(cgImage: image.cgImage!)
let contextSize: CGSize = contextImage.size
let widthRatio = contextSize.height/UIScreen.main.bounds.size.height
let heightRatio = contextSize.width/UIScreen.main.bounds.size.width
let width = (self.imgOverlay?.frame.size.width)!*widthRatio
let height = (self.imgOverlay?.frame.size.height)!*heightRatio
let x = (contextSize.width/2) - width/2
let y = (contextSize.height/2) - height/2
let rect = CGRect(x: x, y: y, width: width, height: height)
let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
let image: UIImage = UIImage(cgImage: imageRef, scale: 0, orientation: image.imageOrientation)
return image
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.