Search code examples
swiftuibezierpath

UIBezierPath - draw multiple rects for a single path


I can draw a single rect with :

let roundedRect = UIBezierPath(roundedRect: rect, cornerRadius: 50)

with this I can not add a new rect to the same path. (I need multiple rects to a single layer)

I can also just draw a rect by moving the point :

    path.move(to: CGPoint(x:point1.x-rectWidth/2.0,y:point1.y) )
    path.addLine(to: CGPoint(x: point1.x-rectWidth/2.0, y: point2.y))
    path.addLine(to: CGPoint(x: point1.x+rectWidth/2.0, y: point2.y))
    path.addLine(to: CGPoint(x: point1.x+rectWidth/2.0, y: point1.y))
    path.addLine(to: CGPoint(x:point1.x-rectWidth/2.0,y:point1.y))

which will not be a rounded rect.

Which approach can I use to get a rounded rect ?


Solution

  • Building a rounded rect yourself is somewhat tricky. I suggest creating rounded rect paths using the UIBezierPath initializer init(roundedRect:cornerRadius:)

    You can use append(_:) to append rounded rect paths to another path:

    var path = UIBezierPath() //Create an empty path
    
    //Add a rounded rect to the path
    path.append(UIBezierPath(roundedRect: rect1, cornerRadius: radius1))
    
    //Add another rounded rect to the path
    path.append(UIBezierPath(roundedRect: rect2, cornerRadius: radius2))
    
    //Lather, rinse, repeat.
    path.append(UIBezierPath(roundedRect: rect3, cornerRadius: radius3))
    

    Edit:

    To animate all of your rectangles drawing from the bottom, like an ink-jet printer, create a CAShapeLayer that's the same size as your view, install a zero-height rectangle at the bottom, and make that layer the mask layer for your view's layer. Then create a CABasicAnimation of the rectangle growing to the full height of the view.