ios - 无法获取 CIFilter: CIPerspectiveCorrection 在指定坐标处裁剪
问题描述
我有一个具有背景图像的单视图应用程序。我想使用 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")
}
}
}
输入:
输出:
解决方案
推荐阅读
- node.js - 有没有办法在 Nodejs 中检测重定向与刷新?
- c# - c# 使用泛型替换方法和类
- c++ - 在向量中找到最小的数
- c# - C#中的参数化查询
- amazon-web-services - 如何在 AWS 中使用 elasticsearch 或 Kibana 控制台
- typescript - 如何将 SonarQube 集成到 Angular 8 项目的詹金斯管道中
- visual-studio-code - 如何在 Visual Studio Code 中仅在单行中包含两个或多个相同的关键字进行评论?
- python - 如何在 Selenium 中找到这些复选框元素
- prolog - Prolog,是否可以使用变量来调用子句?
- angular - ngIf 不在大子指令中工作