Swift中的三角形Imageview

时间:2017-01-12 13:29:28

标签: swift swift3

我想在Swift 3中创建这种类型的视图。我们如何创建我无法做到这一点请帮助任何帮助将不胜感激。在此先感谢

1 个答案:

答案 0 :(得分:1)

您想将图像裁剪为三角形吗?我为这个案例做了一个例子

func createTriangleImage() {
    // your UIImage
    let ballImage = UIImage(named: "ball")!

    // your imageView which you wanted to be triangle. 
    // I made the example via layers as it seems easier to me
    // so you dont need UIImageView here, UIView is enough
    let viewWithImage = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))

    // Layer for your image
    let imageLayer = CALayer()
    // Setting the image
    imageLayer.contents = ballImage.cgImage
    imageLayer.frame = viewWithImage.frame
    viewWithImage.layer.addSublayer(imageLayer)

    //view - is your main view where you wanted to put the triangle image
    view.addSubview(viewWithImage)

    // Creating a triangle path to draw triangle mask later
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 20, y: 0))
    path.addLine(to: CGPoint(x: 40, y: 40))
    path.addLine(to: CGPoint(x: 0, y: 40))
    path.close()

    // Creating a mask layer
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath
    maskLayer.fillColor = UIColor.red.cgColor

    // Setting the mask
    imageLayer.mask = maskLayer
}