如何使 iOS 中的两个矩形相交?

How to intersect two rects in iOS?

我想删除 "blue" 圆圈,只留下一个 "hollow" 中心(所以只有红色层,你可以看到里面的背景)。用 clear 颜色填充内部无效。

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()
    }
}

我该怎么做? intersects 什么都没做。

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()
}

不要忘记给视图一个 backgroundColor.clear 并将其 isOpaque 属性 设置为 false

灵感来自

结果: