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

时间:2017-03-16 19:35:01

标签: ios swift swift3 imageview cashapelayer

我正在尝试将单个imageview转换为右侧对象中的输出。这与How to make imageview with different shape in swift非常相似。然而,这是在swift2。我尝试过它似乎不适用于swift3。

ll

1 个答案:

答案 0 :(得分:0)

试试这样:

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)