UIView with shadow, rounded corners and custom drawRect

前端 未结 16 1437
南旧
南旧 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 05:49

    This is an older question, but I would have just done everything in your custom draw method like below.

    I usually will do this if I know I want to apply a drop shadow to my rounded view (which of course means I don't want to use masksToBounds)

    You also don't have to add an extra "shadow view" to the hierarchy.

    @IBDesignable
    class RoundedView: UIView {
    
    @IBInspectable
    var cornerRadius: CGFloat = 0
    
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        // You could use custom IBInspectable attributes
        // for the stroke and fill color.
        context.setFillColor(UIColor.white.cgColor)
        context.setStrokeColor(UIColor.orange.cgColor)
        // Add a clipping path to get the rounded look
        // you want.
        UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
        // Fill and stroke your background.
        let background = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
        background.lineWidth = 2
        background.fill()
        background.stroke()
    }
    
    private func shadow() {
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowRadius = 5
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize.zero
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        shadow()
    }
    }
    

提交回复
热议问题