[英]Cropping UIImage not yielding expected crop - swift?
我正在嘗試裁剪圖像,但是裁剪無法產生UIImage的預期部分。 圖像顯示方向不正確並鏡像。 這很令人困惑。
@IBOutlet weak var imgPreViewOutlet: UIImageView!
guard
let cgImage = self.imgPreViewOutlet.image.cgImage else {return}
// NORMALISE COORDINATES
let topXn = TOP_LEFT.x/screenWidth
let topYn = TOP_LEFT.y/screenHeight
let widthn = (TOP_RIGHT.x - TOP_LEFT.x)/screenWidth
let heightn = (BOTTOM_RIGHT.y - TOP_RIGHT.y)/screenHeight
// DIMENSION OF CGIMAGE
let cgImgWidth = cgImage.width
let cgImgHeight = cgImage.height
let cropRect = CGRect.init(x: topXn * CGFloat.init(widthn) , y: topYn * CGFloat.init(heightn), width: widthn * CGFloat.init(cgImgWidth), height: heightn * CGFloat.init(cgImgHeight))
if let cgCropImged = cgImage.cropping(to: cropRect){
print("cropRect: \(cropRect)")
self.imgPreViewOutlet.image = UIImage.init(cgImage: cgCropImged)
}
裁剪:
根據要求,下面是一個使用CIPerspectiveCorrection
裁剪圖像的示例。 我下載並使用了Sketch來獲取示例圖像中4個CGPoints
的近似值。
let inputBottomLeft = CIVector(x: 38, y: 122)
let inputTopLeft = CIVector(x: 68, y: 236)
let inputTopRight = CIVector(x: 146, y: 231)
let inputBottomRight = CIVector(x: 151, y: 96)
let filter = CIFilter(name: "CIPerspectiveCorrection")
filter?.setValue(inputTopLeft, forKey: "inputTopLeft")
filter?.setValue(inputTopRight, forKey: "inputTopRight")
filter?.setValue(inputBottomLeft, forKey: "inputBottomLeft")
filter?.setValue(inputBottomRight, forKey: "inputBottomRight")
filter?.setValue(ciOriginal, forKey: "inputImage")
let ciOutput = filter?.outputImage
請注意以下幾點:
CIImage
是左下角 ,而不是左上角 。 您需要“翻轉” Y軸點。 UIImage
具有大小,而CIImage
具有范圍。 這些都是一樣的。 (唯一一次不是使用CIFIlter“創建”某些東西-顏色,平鋪圖像-然后是無限的。) CIVector
可以具有很多屬性。 在這種情況下,我使用的是X / Y簽名,它是CGPoint
的直接副本,只是Y軸被翻轉了。 UIImageView
的示例項目 。 請注意,模擬器的性能遠不能與真實設備上的性能相提並論-我建議在涉及CoreImage的任何時候都使用設備。 另外,我從輸出CIImage到UIImage進行了直接轉換。 如果要提高性能,通常最好使用CIContext
和CoreGraphics
。 根據您的輸入,以下是輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.