如何将圆角半径应用于某些角并添加阴影

时间:2019-02-17 00:01:46

标签: ios swift

是否可以仅将圆角应用于某些角,并同时应用阴影层?

我尝试使用以下扩展名执行此操作,但这对我不起作用:

extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, shadow: Bool = false) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        if shadow {
            self.layer.shadowColor = UIColor.black.cgColor
            self.layer.shadowOffset = CGSize(width: 0, height: 2)
            self.layer.shadowOpacity = 0.3
            self.layer.shadowRadius = 3.0
        }
    }
}

1 个答案:

答案 0 :(得分:0)

因此,根据How to round only specific corners using maskedCorners

的示例,我将一些代码扔进了操场,并创建了一个快速操场。
let view = UIView(frame: CGRect(x: 100, y: 100, width: 500, height: 500))
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 15
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]

view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0)
view.layer.shadowOpacity = 1.0
view.layer.shadowRadius = 4
//view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
view.layer.shouldRasterize = false


let outter = UIView(frame: CGRect(x: 0, y: 0, width: 700, height: 700))
outter.backgroundColor = UIColor.red
outter.addSubview(view)


outter

我做了一些测试:

没有拐角半径

No corner Radius

具有隐藏的拐角半径

With masked corner

减少shawdowRadius

Reduced shadowRadius

并且可以肯定的是,增加了拐角半径

Increased corner radius