我有一个 UIImageView
,带有特定的图像。
我还有一个形状奇怪的 UIBezierPath
。
我想将图像剪切为该形状并返回该形状的新图像。
形式为:
func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
最佳答案
您可以使用mask
来执行此操作。这是一个简单的示例。
class ViewController: UIViewController {
var path: UIBezierPath!
var touchPoint: CGPoint!
var startPoint: CGPoint!
var imageView = UIImageView(image: #imageLiteral(resourceName: "IMG_0715"))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
startPoint = touch.location(in: view)
path = UIBezierPath()
path.move(to: startPoint)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
touchPoint = touch.location(in: view)
}
path.addLine(to: touchPoint)
startPoint = touchPoint
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
cut()
}
private func cut() {
guard let path = path else { return }
imageView = imageView.getCut(with: path)
}
}
extension UIImageView {
func getCut(with bezier: UIBezierPath) -> UIImageView {
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezier.cgPath
self.layer.mask = shapeLayer
return self
}
}
关于swift - 根据UIBezier切割UIImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667946/