If you really want to use masks, you need a complicated view hierarchy that has four main views: The root view (white), the chrome view (the view with all the chrome that will be masked when you add your circle mask; e.g. that top part of your circle that you need masked out), the UI element view(s) that will not be masked when you add your masks to the chrome and the dimming view), and the dimming view (which will also get masked). These latter three need to be subviews of the main view (don't put the messages button on the chrome view, but make it its own view, so when you mask the chrome out, these UI elements won't get masked out).
You end up with something like the following (this is showing after the masks have been added):
![enter image description here](https://istack.dev59.com/r0PNY.webp)
You can then make dimming view visible and mask it and the background view:
@IBAction func didTapButton(_ sender: Any) {
dimmingView.alpha = 0.5
let center = messagingView.center
let radius = messagingView.frame.width * 0.7
mask(center: center, radius: radius, in: messagingView.superview!, on: dimmingView)
mask(center: center, radius: radius, in: messagingView.superview!, on: backgroundView)
}
private func mask(center: CGPoint, radius: CGFloat, in view: UIView, on viewToMask: UIView) {
let point = view.convert(center, to: viewToMask)
let path = UIBezierPath(rect: viewToMask.bounds)
path.addArc(withCenter: point, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true)
let mask = CAShapeLayer()
mask.fillColor = UIColor.white.cgColor
mask.path = path.cgPath
mask.fillRule = kCAFillRuleEvenOdd
viewToMask.layer.mask = mask
}
Thus with the dimming view not visible and no masks in place, you have the before view:
![enter image description here](https://istack.dev59.com/CnPoo.webp)
And then after the dimming view is made visible and both it and the "chrome" view are masked:
![enter image description here](https://istack.dev59.com/Fuhyw.webp)
drawRect
中操作图层是不可取的,因为它发生在渲染周期的太晚阶段。如果您想添加蒙版,请在layoutSubviews
中进行操作。 - Rob.pi
而不是键入3.14
。此外,我不确定为什么要创建CGMutablePath
而不是直接创建UIBezierPath
。 - Rob