view.layer.masksToBounds
masksToBounds
→ sublayers are clipped to the layer’s bounds
他會依layer的bounds將一塊mask蓋上layer裁切,包含任何bounds外的效果,若不只一個mask存在,則mask的效果是會疊加
view.clipsToBounds
clipsToBounds
→ subviews are confined to the bounds of the view
直白的就是將bounds外的子畫面才切掉
borderView.layer.cornerRadius = 10
borderView.layer.masksToBounds = true
shadowView.backgroundColor = .clear //與cornerRadius擇一
shadowView.layer.cornerRadius = 10 //與backgroundColor擇一
shadowView.layer.masksToBounds = false
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowRadius = 4
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowOffset = CGSize(width: 2, height: 2)
<aside> 💡 但這時候會跑出另一個問題 “The layer is using dynamic shadows which are expensive to render. If possible try setting `shadowPath'” 每次呼叫cell都要render一次陰影效果,很浪費資源因此不建議
</aside>
class ShadowView: UIView {
override var bounds: CGRect {
didSet {
setupShadow()
}
}
private func setupShadow() {
self.layer.cornerRadius = 10
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowRadius = 3
self.layer.shadowOpacity = 0.4
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}