[英]How to customize the camera view and capture the part in the overlay?
我需要构建类似于以下内容的自定义相机视图: 示例图像
我使用了AVFoundation并将UIImageView放在AVCaptureVideoPreviewLayer上,它看起来几乎是相同的(尽管我不确定这是否正确,这就是我这样写标题的方式)。 我正在捕获图像并将其保存到图库,但是我只需要中间矩形区域中的图像即可。
有什么建议怎么做吗?
提前致谢!
您需要在叠加图像视图的上下文中裁剪图像。在下面的功能中传递捕获的图像可能会有所帮助。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.