`UIBezierPath.fill()` 没有填充 `draw()` 的内部

`UIBezierPath.fill()` does not fill inside of `draw()`

我正在从半透明 UIView 中裁剪出一个矩形。当我使用 UIRectFill() 时,它按预期工作。但是,当我创建一个带有圆角的 UIBezierPath 时,fill() 似乎没有做任何事情。奇怪的是,在同一路径上调用 stroke() 工作正常。

作品:

override func draw(_ rect: CGRect) {
    screenColor.set()
    UIRectFill(self.bounds)

    let viewfinderRect = CGRect(x: 50, y: 50, width: 100, height: 100)

    UIColor.clear.setFill()
    UIRectFill(viewfinderRect)  //Works!
}

不工作:

override func draw(_ rect: CGRect) {
    screenColor.set()
    UIRectFill(self.bounds)

    let viewfinderRect = CGRect(x: 50, y: 50, width: 100, height: 100)
    let path = UIBezierPath(roundedRect: viewFinderRect, cornerRadius:  10.0)

    UIColor.clear.setFill()
    path.fill()             // Does not work!
    //path.stroke()         // Works!
}

你画的不一样blend mode

documentation for UIRectFill 说:

Fills the specified rectangle using the fill color of the current graphics context and the kCGBlendModeCopy blend mode.

(在 Swift 中,此混合模式的名称是 CGBlendMode.copy。)

当您使用这种混合模式时,指定的填充颜色会被复制到上下文中,替换下面的颜色。由于您的填充颜色很清晰,因此您有效地在视图中切了一个洞。

但是,当您调用 path.fill() 时,它使用上下文中的默认混合模式,即 CGBlendMode.normal。这会绘制 over 上下文中已有的填充颜色。由于您的填充颜色很清晰,因此没有可见效果。

试试这个:

UIColor.clear.setFill()
path.fill(with: CGBlendMode.copy, alpha: 1.0)

或者这样:

UIColor.clear.setFill()
UIGraphicsGetCurrentContext()?.setBlendMode(CGBlendMode.copy)
path.fill()

或者您甚至可以一行完成:

path.fill(with: CGBlendMode.clear, alpha: 1.0)