Search code examples
iosswiftswift3imageviewcashapelayer

How to convert image view to custom shape (swift3)


I am trying to convert the a single imageview to output in the in the object on the right. This is a very similar question to How to make imageview with different shape in swift. However that was in swift2. I tried it and it does not seem to work in swift3.

ll


Solution

  • Try like this:

    extension UIImageView {
        func addMask(_ bezierPath: UIBezierPath) {
            let pathMask = CAShapeLayer()
            pathMask.path = bezierPath.cgPath
            layer.mask = pathMask
        }
    }
    

    Testing playground:

    let myPicture = UIImage(data: try! Data(contentsOf: URL(string:"https://i.sstatic.net/Xs4RX.jpg")!))!
    let iv = UIImageView(image: myPicture)
    
    let bezierPath = UIBezierPath()
    bezierPath.move(to: iv.center)
    bezierPath.addLine(to: CGPoint(x: iv.frame.maxX, y: 0))
    bezierPath.addLine(to: CGPoint(x: iv.frame.maxX, y: iv.frame.maxY))
    bezierPath.addLine(to: CGPoint(x: 0, y: iv.frame.maxY))
    bezierPath.addLine(to: .zero)
    bezierPath.close()
    
    iv.addMask(bezierPath)