简体   繁体   English

如何自定义相机视图并捕获叠加中的零件?

[英]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). 我使用了AVFoundation并将UIImageView放在AVCaptureVideoPreviewLayer上,它看起来几乎是相同的(尽管我不确定这是否正确,这就是我这样写标题的方式)。 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. 实际上,Nishant Bhindi的答案需要一些更正。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM