iosswift5uibezierpathcgpath

When using a CAShapeLayer, is there any advantage at all to using a UIBezierPath over just constructing a cgPath?


When I have

private lazy var aLine: RepairedCAShapeLayer {
    let v = RepairedCAShapeLayer()
    v.contentsScale = UIScreen.main.scale
    v.strokeColor = cfp.color.cgColor
    v.fillColor = nil
    v.lineWidth = 2
    v.lineJoin = .miter
    return v
}

I just realized that I inevitably ...

override func layoutSubviews() {
    super.layoutSubviews()
    aLine.path = fancyBezDrawing().cgPath

Where fancyBezDrawing() is a pile of code that creates a UIBezierPath.

I also just glanced in a few client code bases and the same. And innumerable examples of same on SO.

But I suppose, one could just

override func layoutSubviews() {
    super.layoutSubviews()
    aLine.path = fancyCGPDrawing()

Where, fancyCGPDrawing simply creates a ... CGPath.

Is there something I'm missing? Is there any reason one should make paths as UIBezierPath rather than just directly as CGPath, for layers??


Solution

  • I don't believe there's any major advantage in Swift to using UIBezierPath over a CGPath.
    My assumption is that UIBezierPath exists to make creating a CGPath easier when writing Objective-C.
    This is because the CGPath API is a C based API and is not very discoverable - for example to move a path to a point in Objective-C to a point you'd use this global function:

    void CGPathMoveToPoint(CGMutablePathRef path, const CGAffineTransform *m, CGFloat x, CGFloat y)
    

    Where as with UIBezierPath, all the available functions are instance methods, in this case:

    - (void) moveToPoint:(CGPoint) point;
    

    This doesn't matter in Swift because the CGPath/CGMutablePath APIs have been nicely adapted into structs and instance functions.