Search code examples
iosswiftintersectionuibezierpath

Add two paths together using UIBezierPath in Swift


I have 2 lines drawn using UIBezierPath, how can i combine point to form a shape inform of letter X. I want to join both lines together

Path 1

let path1 = UIBezierPath()
path1.move(to: .zero)
path1.addLine(to: CGPoint(x: 100, y: 100))
path1.close()
path1.lineWidth = 1.0
UIColor.blue.set()
path1.stroke()
path1.fill()

Path 2

let path2 = UIBezierPath()
path2.move(to: .zero)
path2.addLine(to: CGPoint(x: 50, y: 50))
path2.close()
path2.lineWidth = 1.0
UIColor.red.set()
path2.stroke()
path2.fill()

Solution

  • You should use proper CGPoint values

    If your view bounds value is (0,0,100,100)

    • Move to (0,0)
    • Addline to (100,100)
    • Mode to (0,100)
    • Addline to (100,0)

    Try this

    let path = UIBezierPath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
    path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
    path.close()
    path.lineWidth = 1.0
    UIColor.blue.set()
    path.stroke()
    path.fill()