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

Posted

技术标签:

【中文标题】如何自定义相机视图并捕获叠加层中的部分?【英文标题】:How to customize the camera view and capture the part in the overlay? 【发布时间】:2017-11-01 10:52:14 【问题描述】:

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

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

有什么建议吗?

提前致谢!

【问题讨论】:

【参考方案1】:

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

【讨论】:

【参考方案2】:

您需要在覆盖 imageView 的上下文中裁剪图像。将捕获的图像传递到下面的函数中,这可能会对您有所帮助。

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

【讨论】:

感谢您的回复!...问题是它返回图像的左上角...不是覆盖边框中的图像...质量很差:( 在预览视图中添加叠加图像视图。

以上是关于如何自定义相机视图并捕获叠加层中的部分?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用自定义相机 API 制作圆形框架布局并捕获圆形图像?

在 applozic 中自定义相机叠加层

具有自定义视图的相机

如何在Android中自定义相机布局?

如何在Android中制作自定义相机布局?

Flutter 相机叠加层