代码之家  ›  专栏  ›  技术社区  ›  Cesare

如何在iOS中相交两个矩形?

  •  0
  • Cesare  · 技术社区  · 6 年前

    我想删除“蓝色”的圆圈,只是有一个“空心”的中心(所以只有红色层,你可以看到里面的背景)。在里面填上 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

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   André Slotta    6 年前
    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 .

    Draw transparent UIBezierPath line inside drawRect .

    result