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

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

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

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

有什么建议吗?

提前致谢!

您需要在覆盖 imageView.Pass 捕获的图像的上下文中裁剪图像,以下功能可能对您有所帮助。

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
}

实际上,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
}