裁剪UIImage不会产生预期的收成 - 迅速?

问题描述 投票:1回答:2

我正在尝试裁剪图像,但裁剪不会产生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)
    }

enter image description here

裁剪:

enter image description here

ios swift core-image
2个回答
2
投票

根据要求,这是使用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轴被翻转。
  • 我有一个使用sample project hereUIImageView。请注意,模拟器上的性能远不及真实设备的性能 - 我建议随时使用CoreImage时使用设备。此外,我从输出CIImage直接转换为UIImage。如果你正在寻找性能,通常最好使用CIContextCoreGraphics

根据您的输入,这是输出:

enter image description here


3
投票

核心图形坐标来自左下角的原点,UIKit坐标来自左上角。我想你们两个都很困惑。

这可能有所帮助:

How to compensate the flipped coordinate system of core graphics for easy drawing?

© www.soinside.com 2019 - 2024. All rights reserved.