我創建了一個應用程式,用戶可以在其中拍照,我想添加一個自定義裁剪功能,該功能類似于 Snapchat 或 PhotoShops 魔術棒工具。我從 Apple 開發者網站找到了下面的代碼,它允許我將捕獲的影像裁剪成CGRect.
func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage?
{
let imageViewScale = max(inputImage.size.width / viewWidth,
inputImage.size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
y:cropRect.origin.y * imageViewScale,
width:cropRect.size.width * imageViewScale,
height:cropRect.size.height * imageViewScale)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}
而不是使用 aGCRect如何在影像中圍繞物件繪制并將其用作cropZone? 任何幫助將不勝感激。
uj5u.com熱心網友回復:
你問的是一項相當復雜的任務,超出了 SO 問題的范圍。我可以給你一個你需要做的大綱:
實作一個繪圖方法,讓用戶在影像上繪圖并從該繪圖創建一個封閉的 CGPath/UIBezierPath
將該路徑安裝到影像視圖的圖層的蒙版屬性中。這會將影像的部分隱藏在外面
找到用戶繪制的形狀的邊界矩形,然后像上面一樣裁剪到那個矩形。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/314770.html
