无法获取CIFilter:CIPerspectiveCorrection无法在指定坐标处进行裁剪

时间:2018-09-18 12:28:18

标签: ios swift core-image

我有一个具有背景图像的单视图应用程序。我想使用CIPerspectiveCorrection从此背景图像中裁剪出四边形并进行裁剪。我的尝试在下面,但我没有得到所需的作物。所需的作物以黄色的四边形表示。

@IBOutlet weak var imgView: UIImageView!

let layer = CAShapeLayer.init()
let topLeft = CGPoint.init(x: 60, y: 70)
let topRight = CGPoint.init(x: 300, y: 80)
let bottomRight = CGPoint.init(x: 320, y: 250)
let bottomLeft = CGPoint.init(x: 50, y: 280)

var nTopLeft: CGPoint!
var nTopRight: CGPoint!
var nbottomRight: CGPoint!
var nbottomLeft: CGPoint!

var widthImg: CGFloat!
var heightImg: CGFloat!

override func viewDidLoad() {
    super.viewDidLoad()


    // DETERMINE IMAGE WIDTH AND HEIGHT
    widthImg =  imgView.frame.width
    heightImg = imgView.frame.height

    // DRAW QUADRILATERAL - DESIRED AREA OF CROP
    let rec = UIBezierPath.init()
    rec.move(to: CGPoint.init(x: topLeft.x, y: topLeft.y))
    rec.addLine(to: CGPoint.init(x: topRight.x, y: topRight.y))
    rec.addLine(to: CGPoint.init(x: bottomRight.x, y: bottomRight.y))
    rec.addLine(to: CGPoint.init(x: bottomLeft.x, y: bottomLeft.y))
    rec.close()

    layer.opacity = 0.4
    layer.path = rec.cgPath
    layer.lineWidth = 5
    layer.strokeColor = UIColor.yellow.cgColor
    layer.frame = self.imgView.frame
    imgView.layer.addSublayer(layer)

}



/* CROP  IMAGE */
@IBAction func cropBtn(_ sender: Any) {

    self.layer.removeFromSuperlayer()

    print("crop pressed!")

    let uiImage = self.imgView.image
    let ciImage = CIImage.init(image: uiImage!)

    let inputBottomLeft = CIVector.init(x: bottomLeft.x , y: heightImg - bottomLeft.y)
    let inputTopLeft = CIVector.init(x: topLeft.x, y: heightImg - topLeft.y)
    let inputTopRight = CIVector.init(x: topRight.x , y: heightImg - topRight.y)
    let inputBottomRight = CIVector.init(x: bottomRight.x , y: heightImg - bottomRight.y)

    let filter = CIFilter.init(name: "CIPerspectiveCorrection")
    filter?.setValue(inputTopLeft, forKey: "inputTopLeft")
    filter?.setValue(inputTopRight, forKey: "inputTopRight")
    filter?.setValue(inputBottomRight, forKey: "inputBottomRight")
    filter?.setValue(inputBottomLeft, forKey: "inputBottomLeft")
    filter?.setValue(ciImage, forKey: "inputImage")

    print("imgView.frame: \(imgView.frame)")

    DispatchQueue.main.async {
        if let ciOutput = filter?.outputImage{
            let uiImg = UIImage.init(ciImage: ciOutput)
            self.imgView.image = uiImg
            print("success")
        }else{
            print("ciOutput fail")
        }
    }
}

输入:

enter image description here

输出:

enter image description here

0 个答案:

没有答案