Cesare
Cesare

Reputation: 9419

How to intersect two rects in iOS?

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

Upvotes: 0

Views: 210

Answers (1)

André Slotta
André Slotta

Reputation: 14030

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

Upvotes: 1

Related Questions