UIView Shadow 使用 BezierPath 大量偏移阴影

UIView Shadow using BezierPath massively offsets the shadow

我已将阴影添加到 UIView,但得到以下结果:

代码如下:

mainView.layer.cornerRadius = 8
mainView.layer.shadowColor = UIColor.black.cgColor
mainView.layer.shadowOpacity = 0.2
mainView.layer.shadowRadius = 10
mainView.clipsToBounds = false
mainView.backgroundColor = UIColor.blue
mainView.layer.shadowPath = UIBezierPath(roundedRect: mainView.frame, cornerRadius: 8).cgPath

鉴于我为 shadowPath 提供了与蓝色视图 (mainView) 相同的框架,我不明白为什么阴影偏移如此之大。我知道我可以使用 shadowOffset 属性 来解决这个问题,但我尝试使用 shadowPath 的全部原因是 而不是 使用 shadowOffset ,因为它可能有一些大规模的性能问题。

更新:将mainView.frame修改为mainView.bounds后,阴影适当对齐。然而,阴影似乎仍然在 mainView 的顶部略有偏移(上面有更强的阴影):

请注意阴影是在视图的坐标中指定的,因此您应该使用 mainView.bounds

mainView.layer.shadowPath = UIBezierPath(roundedRect: mainView.bounds, cornerRadius: 8).cgPath

换句话说,您想要一个原点为 (0, 0) 的矩形,而不是 mainView.

的位置

the shadow seems to still be slightly offset at the top of the mainView

这是因为shadowOffset有一个默认值(0.0, -3.0)

https://developer.apple.com/documentation/quartzcore/calayer/1410970-shadowoffset

为避免这种情况,您可以使用 offsetBy

mainView.layer.shadowPath = UIBezierPath(roundedRect: mainView.bounds.offsetBy(dx: 0.0, dy: 3.0), cornerRadius: 8).cgPath

或者简单地说,将 .zero 传递给 shadowOffset

mainView.layer.shadowOffset = .zero