如何将图像视图转换为自定义形状(swift3)

How to convert image view to custom shape (swift3)

我正在尝试将单个图像视图转换为在右侧对象中输出。这是一个与 非常相似的问题。然而,那是在 swift2 中。我试过了,它似乎在 swift3 中不起作用。

这样试试:

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

测试游乐场:

let myPicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/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)