UIBezierPath Triangle with rounded edges

前端 未结 6 1452
耶瑟儿~
耶瑟儿~ 2020-11-30 18:00

I have designed this code to generate a Bezier Path that is used as a path for a CAShapeLayer to mask a UIView (the view\'s height and width are variable)

This code

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 18:30

    Rounded Triangle in Swift 4

    A playground based on @an0's answer above.

    import UIKit
    import PlaygroundSupport
    import CoreGraphics
    
    var view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    view.backgroundColor = .black
    PlaygroundPage.current.liveView = view
    
    let triangle = CAShapeLayer()
    triangle.fillColor = UIColor.systemGreen.cgColor
    triangle.path = createRoundedTriangle(width: 220, height: 200, radius: 15)
    triangle.position = CGPoint(x: 140, y: 130)
    view.layer.addSublayer(triangle)
    
    func createRoundedTriangle(width: CGFloat, height: CGFloat, radius: CGFloat) -> CGPath {
        let point1 = CGPoint(x: -width / 2, y: height / 2)
        let point2 = CGPoint(x: 0, y: -height / 2)
        let point3 = CGPoint(x: width / 2, y: height / 2)
    
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: height / 2))
        path.addArc(tangent1End: point1, tangent2End: point2, radius: radius)
        path.addArc(tangent1End: point2, tangent2End: point3, radius: radius)
        path.addArc(tangent1End: point3, tangent2End: point1, radius: radius)
        path.closeSubpath()
    
        return path
    }
    

提交回复
热议问题