-1

I have tried many solutions available in over stackoverflow ,but none work. Here is the extension I wrote for dropShadow effect.

extension UIView {
    func dropShadow(color: UIColor, opacity: Float = 0.4, offSet: CGSize, shadowRadius: CGFloat = 1, scale: Bool = true, cornerRadius: CGFloat) {
        let shadowLayer = CAShapeLayer()
        shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
        shadowLayer.fillColor = UIColor.white.cgColor
        shadowLayer.shadowColor = color.cgColor
        shadowLayer.shadowPath = shadowLayer.path
        shadowLayer.shadowOffset = offSet
        shadowLayer.shadowOpacity = opacity
        shadowLayer.shadowRadius = shadowRadius
        layer.insertSublayer(shadowLayer, at: 0)
    }
}

And here I am using this extension like :

override func layoutSubviews() {
        contentView.backgroundColor = UIColor.clear
        backgroundColor = UIColor.clear
        backView.dropShadow(color: .black, offSet: CGSize(width: 0.0, height: 3.0), cornerRadius: 20)
        backView.layer.cornerRadius = 20
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.5)
        gradientLayer.frame.size = self.backView.frame.size
        backView.layer.insertSublayer(gradientLayer, at:1)
    }

And here is the result which I got :

Screenshot

As you can see in the screenshot that shadow radius I am getting but the UIView radius is still same. So how to get that cornerradius. I am struggling from morning. Any help will be highly appreciated. Thanks in advance.

Piyush
  • 492
  • 5
  • 22

1 Answers1

0

I have forgot to add corner radius of gradientLayer.

override func layoutSubviews() {
        contentView.backgroundColor = UIColor.clear
        backgroundColor = UIColor.clear
        backView.dropShadow(color: .black, offSet: CGSize(width: 0.0, height: 3.0), cornerRadius: 10)
        backView.layer.cornerRadius = 20
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.5)
        gradientLayer.cornerRadius = 10 .  <--- this was missing
        gradientLayer.frame.size = self.backView.frame.size
        backView.layer.insertSublayer(gradientLayer, at:1)
    }
Piyush
  • 492
  • 5
  • 22
  • add this after backView,layer.cornerRadius: backView.layer.masksToBounds = true the gradient take the same corner automatically... if this does not happen add this line to gradient: gradientLayer.layer.clipsToBounds = true – Fabio Dec 13 '19 at 18:19