如何自定义摄像机视图并捕获叠加层中的部分?

时间:2017-11-01 10:52:15

标签: ios swift camera uiimage avfoundation

我需要构建一个类似于此的自定义相机视图:example image

我已经使用了AVFoundation并在AVCaptureVideoPreviewLayer上放置了一个UIImageView,它看起来几乎一样(虽然我不确定这是不是正确的方式,这就是我写这样的标题)。我正在捕捉图像并将其保存到图库中,但我只需要中间矩形的图像。

有什么建议吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

您需要在叠加图像的上下文中裁剪图像。在下面的功能中捕获可能对您有帮助的图像。

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
}

答案 1 :(得分:0)

实际上Nishant Bhindi的答案需要一些修正。下面的代码将完成工作:

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
}