簡體   English   中英

裁剪UIImage無法獲得預期的收成-快速嗎?

[英]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)
    }

在此處輸入圖片說明

裁剪:

在此處輸入圖片說明

核心圖形坐標從左下角的原點開始,UIKit坐標從左上角開始。 我認為您混淆了兩者。

這可能會有所幫助:

如何補償核心圖形的翻轉坐標系以便於繪制?

根據要求,下面是一個使用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

請注意以下幾點:

  • 永遠不要忘記CoreImage最重要的事情是,起源CIImage左下角 ,而不是左上角 您需要“翻轉” Y軸點。
  • UIImage具有大小,而CIImage具有范圍。 這些都是一樣的。 (唯一一次不是使用CIFIlter“創建”某些東西-顏色,平鋪圖像-然后是無限的。)
  • CIVector可以具有很多屬性。 在這種情況下,我使用的是X / Y簽名,它是CGPoint的直接副本,只是Y軸被翻轉了。
  • 這里有一個使用UIImageView示例項目 請注意,模擬器的性能遠不能與真實設備上的性能相提並論-我建議在涉及CoreImage的任何時候都使用設備。 另外,我從輸出CIImage到UIImage進行了直接轉換。 如果要提高性能,通常最好使用CIContextCoreGraphics

根據您的輸入,以下是輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM