UIView Round Corners with Shadow

前端 未结 3 1817
误落风尘
误落风尘 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: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.

提交回复
热议问题