UIView切出任意数量的透明孔

时间:2018-10-21 03:12:14

标签: ios

我想要一个UIView可以具有任意数量的透明孔。我用UsesEvenOddFillRule尝试了UIBezierPath是真实的。但是没有运气,只有一个洞是可以的,任何数目的洞都行不通。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码绘制圆形/椭圆形:

class HolyView: UIView {

  var holes: [CGRect] = [] {
      didSet {
          setNeedsDisplay()
      }
  }

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

      for hole in holes {
          let intersection = rect.intersection(hole)
          let context = UIGraphicsGetCurrentContext()

          if intersection.intersects(rect) {
              context?.setFillColor(self.backgroundColor?.cgColor ?? UIColor.clear.cgColor)
              context?.setBlendMode(CGBlendMode.clear)
              context?.fillEllipse(in: intersection)
          }
       }
    }
}

或使用BezierPath:

class BeziHolyView: UIView {

  var holes: [CGRect] = [] {
      didSet {
          setNeedsDisplay()
      }
  }

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

      let context = UIGraphicsGetCurrentContext()
      context?.clear(rect)

      let clipPath = UIBezierPath(rect: self.bounds)
      for hole in holes {
          clipPath.append(UIBezierPath(roundedRect: hole, cornerRadius: hole.height/2))
      }

      clipPath.usesEvenOddFillRule = true
      clipPath.addClip()
      backgroundColor?.setFill()
      clipPath.fill()
  }
}

用法:

let view = HolyView/BeziHolyView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.green
view.holes = [CGRect(x: 40, y: 20, width: 20, height: 20),
              CGRect(x: 80, y: 30, width: 20, height: 20)]

结果:

enter image description here