[英]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.