Search code examples
swiftcore-graphicsuibezierpath

Drawing differences of 2 UIBezierPath


I want to draw differences between 2 UIBezierPath (see screenshot) in order to draw only rounded corners as you can see on my screenshot (figure C)

enter image description here

Here is my code:

let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)

let rectanglePath = UIBezierPath(rect: rect)
CGContextAddPath(context, rectanglePath.CGPath)
CGContextEOClip(context)

let roundedRectanglePath = UIBezierPath(roundedRect: productRect, byRoundingCorners: roundedCorners, cornerRadii: CGSize(width: 6, height: 6))
CGContextAddPath(context, roundedRectanglePath.CGPath)
CGContextFillPath(context)

CGContextRestoreGState(context)

Unfortunately it doesn't work. I only draw rounded black rectangle.

Do you have an idea?

Thanks a lot.


Solution

  • You can use one path:

    let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
    path.append(UIBezierPath(rect: bounds))
    path.usesEvenOddFillRule = true
    
    UIColor.black.setFill()
    path.fill()
    

    Or you can use CoreGraphics:

    let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
    path.append(UIBezierPath(rect: bounds))
    
    let context = UIGraphicsGetCurrentContext()!
    context.addPath(path.cgPath)
    context.setFillColor(UIColor.black.cgColor)
    context.fillPath(using: .evenOdd)
    

    That yields:

    enter image description here

    See previous revision of this answer for Swift 2 rendition.