UIView Round Corners with Shadow

前端 未结 3 1753
误落风尘
误落风尘 2020-12-31 05:22

I am trying to display a UIView with round corners and with a drop shadow. But the problem is that maskToBounds property only works for either of the case.

If maskT

相关标签:
3条回答
  • 2020-12-31 05:25

    You can do it with a single view by applying following:

    1. Firstly add a corner radius

    yourview.layer.cornerRadius = 5.0
    

    2. Call a function below

    shadowToView(view : yourview)
    
    
    func shadowToView(view : UIView){
        view.layer.shadowOffset = CGSize(width: 0, height: 3)
        view.layer.shadowOpacity = 0.6
        view.layer.shadowRadius = 3.0
        view.layer.shadowColor = UIColor.darkGray.cgColor
    }
    
    0 讨论(0)
  • 2020-12-31 05:28

    The accepted answer didn't include any code, so here is an example in Swift (See the original question for the OP's solution in Obj-C).

    Like the accepted answer, this solution uses separate views for the shadow and the corner radius.

    // add the shadow to the base view
    baseView.backgroundColor = UIColor.clear
    baseView.layer.shadowColor = UIColor.black.cgColor
    baseView.layer.shadowOffset = CGSize(width: 3, height: 3)
    baseView.layer.shadowOpacity = 0.7
    baseView.layer.shadowRadius = 4.0
    
    // improve performance
    baseView.layer.shadowPath = UIBezierPath(roundedRect: baseView.bounds, cornerRadius: 10).cgPath
    baseView.layer.shouldRasterize = true
    baseView.layer.rasterizationScale = UIScreen.main.scale
    
    // add the border to subview
    let borderView = UIView()
    borderView.frame = baseView.bounds
    borderView.layer.cornerRadius = 10
    borderView.layer.borderColor = UIColor.black.cgColor
    borderView.layer.borderWidth = 1.0
    borderView.layer.masksToBounds = true
    baseView.addSubview(borderView)
    
    // add any other subcontent that you want clipped
    let otherSubContent = UIImageView()
    otherSubContent.image = UIImage(named: "lion")
    otherSubContent.frame = borderView.bounds
    borderView.addSubview(otherSubContent)
    

    My full answer is here.

    0 讨论(0)
  • 2020-12-31 05:50

    Create two views. one with the drop shadow (and don't forget to set the shadowPath) in which you add a subview with cornerRadius and maskToBounds.

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