Search code examples
swiftuiimageviewuibezierpath

Cutting a UIImageView according to UIBezier?


I have a UIImageView, with a certain image. I also have a UIBezierPath in some strange shape. I would like to cut the image to that shape and return a new image in that shape.

enter image description here

In the form of :

func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView

Solution

  • You can use mask to do so. Here's a quick example.

    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
        }
    }