UIView with shadow, rounded corners and custom drawRect

前端 未结 16 1461
南旧
南旧 2020-12-02 05:22

I have to create a custom UIView that will have round corners, a border, a shadow and its drawRect() method is overridden to provide custom drawing

16条回答
  •  广开言路
    2020-12-02 06:11

    This is a tricky one. UIView's clipsToBounds is necessary to get the rounded corners. But CALayer's masksToBounds has to be false so the shadow is visible. Somehow, everything works if drawRect is not overridden, but actually it shouldn't.

    The solution is to create a superview to provide the shadow (in the demonstration below this is the shadowView). You can test the following in Playground:

    class MyView : UIView {
        override func drawRect(rect: CGRect) {
            let c = UIGraphicsGetCurrentContext()
            CGContextAddRect(c, CGRectMake(10, 10, 80, 80))
            CGContextSetStrokeColorWithColor(c , UIColor.redColor().CGColor)
            CGContextStrokePath(c)
        }
    }
    
    let superview = UIView(frame: CGRectMake(0, 0, 200, 200))
    
    let shadowView = UIView(frame: CGRectMake(50, 50, 100, 100))
    shadowView.layer.shadowColor = UIColor.blackColor().CGColor
    shadowView.layer.shadowOffset = CGSizeZero
    shadowView.layer.shadowOpacity = 0.5
    shadowView.layer.shadowRadius = 5
    
    let view = MyView(frame: shadowView.bounds)
    view.backgroundColor = UIColor.whiteColor()
    view.layer.cornerRadius = 10.0
    view.layer.borderColor = UIColor.grayColor().CGColor
    view.layer.borderWidth = 0.5
    view.clipsToBounds = true
    
    shadowView.addSubview(view)
    superview.addSubview(shadowView)
    

    Result:

    enter image description here

提交回复
热议问题