R.Radev
R.Radev

Reputation: 91

How to customize the camera view and capture the part in the overlay?

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!

Upvotes: 0

Views: 1722

Answers (2)

Viktor Todorov
Viktor Todorov

Reputation: 390

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
}

Upvotes: 1

Nishant Bhindi
Nishant Bhindi

Reputation: 2252

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
}

Upvotes: 1

Related Questions