Swift - Problems with corner radius and drop shadow

前端 未结 14 1373
失恋的感觉
失恋的感觉 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)
    
    0 讨论(0)
  • 2020-11-28 19:00

    If somebody need add shadows to rounded buttons in Swift 3.0, here is a good method to do it.

    func addShadowForRoundedButton(view: UIView, button: UIButton, shadowColor: UIColor, shadowOffset: CGSize, opacity: Float = 1) {
        let shadowView = UIView()
        shadowView.backgroundColor = shadowColor
        shadowView.layer.opacity = opacity
        shadowView.layer.cornerRadius = button.bounds.size.width / 2
        shadowView.frame = CGRect(origin: CGPoint(x: button.frame.origin.x + shadowOffset.width, y: button.frame.origin.y + shadowOffset.height), size: CGSize(width: button.bouds.width, height: button.bounds.height))
        self.view.addSubview(shadowView)
        view.bringSubview(toFront: button)
    }
    

    Use this method in func viewDidLayoutSubviews() as bellow:

    override func viewDidLayoutSubviews() {
        addShadowForRoundedButton(view: self.view, button: button, shadowColor: .black, shadowOffset: CGSize(width: 2, height: 2), opacity: 0.5)
    }
    

    The effect of this method is:

    0 讨论(0)
提交回复
热议问题