0

I would like to remove the "blue" circle and just have a "hollow" center (so there's only the red layer and you can see the background inside). Filling the inside with the clear color doesn't work.

class AddButtonView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        // Outer circle
        UIColor.red.setFill()
        let outerPath = UIBezierPath(ovalIn: rect)
        outerPath.fill()

        // Center circle
        UIColor.blue.setFill()
        let centerRect = rect.insetBy(dx: rect.width * 0.55 / 2, dy: rect.height * 0.55 / 2)
        let centerPath = UIBezierPath(ovalIn: centerRect)
        centerPath.fill()
    }
}

How can I do it? intersects didn't do anything.

enter image description here

Cesare
  • 9,139
  • 16
  • 78
  • 130

1 Answers1

1
override func draw(_ rect: CGRect) {
    super.draw(rect)

    // Outer circle
    UIColor.red.setFill()
    let outerPath = UIBezierPath(ovalIn: rect)
    outerPath.fill()

    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.saveGState()
    context.setBlendMode(.destinationOut)

    // Center circle
    UIColor.blue.setFill()
    let centerRect = rect.insetBy(dx: rect.width * 0.55 / 2, dy: rect.height * 0.55 / 2)
    let centerPath = UIBezierPath(ovalIn: centerRect)
    centerPath.fill()

    context.restoreGState()
}

Do not forget to give the view a backgroundColor of .clear and set its isOpaque property to false.

Inspired by Draw transparent UIBezierPath line inside drawRect.

Result: result

André Slotta
  • 13,774
  • 2
  • 22
  • 34
  • I'm sorry, this only adds a black background to the view. It does not solve my question. – Cesare Dec 15 '18 at 13:37
  • Updated my answer with the result. Did you set the view's `backgroundColor` to `.clear`? And `isOpaque` to false? – André Slotta Dec 15 '18 at 13:38
  • Thanks, settings `isOpaque` to false did the trick! You may want to update your answer with that info. – Cesare Dec 15 '18 at 13:43