Swift - Problems with corner radius and drop shadow

前端 未结 14 1448
失恋的感觉
失恋的感觉 2020-11-28 18:35

I\'m trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I\

14条回答
  •  星月不相逢
    2020-11-28 18:58

    Using CAShapeLayer and UIBezierPath we can easily add shadow and corner radius to UIView and the class derived from it like UIButton, UIImageView, UILabel etc.

    We will add UIView Extension and the good point of this is, you only need to write just one line of code to achieve this.

    You can round specific corner as well Just add below UIView Extension in your project:

     extension UIView {
    
      func addShadow(shadowColor: UIColor, offSet: CGSize, opacity: Float, shadowRadius: 
      CGFloat, cornerRadius: CGFloat, corners: UIRectCorner, fillColor: UIColor = .white) {
    
        let shadowLayer = CAShapeLayer()
        let size = CGSize(width: cornerRadius, height: cornerRadius)
        let cgPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size).cgPath //1
        shadowLayer.path = cgPath //2
        shadowLayer.fillColor = fillColor.cgColor //3
        shadowLayer.shadowColor = shadowColor.cgColor //4
        shadowLayer.shadowPath = cgPath
        shadowLayer.shadowOffset = offSet //5
        shadowLayer.shadowOpacity = opacity
        shadowLayer.shadowRadius = shadowRadius
        self.layer.addSublayer(shadowLayer)
      }
    }
    

    Now just write below code to add shadow and corner radius

      self.myView.addShadow(shadowColor: .black, offSet: CGSize(width: 2.6, height: 2.6), 
      opacity: 0.8, shadowRadius: 5.0, cornerRadius: 20.0, corners: [.topRight, .topLeft], 
      fillColor: .red)
    

提交回复
热议问题