UIView with shadow, rounded corners and custom drawRect

前端 未结 16 1398
南旧
南旧 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条回答
  •  萌比男神i
    2020-12-02 05:57

    SWIFT 3 Solution

    Adapted from Mundi's answer

    class MyView : UIView {
            override func draw(_ rect: CGRect) {
                let c = UIGraphicsGetCurrentContext()
                c!.addRect(CGRect(x: 10, y: 10, width: 80, height: 80))
                c!.setStrokeColor(UIColor.red.cgColor)
                c!.strokePath()
            }
        }
    
    let superview = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    
    let shadowView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
    shadowView.layer.shadowColor = UIColor.black.cgColor
    shadowView.layer.shadowOffset = CGSize.zero
    shadowView.layer.shadowOpacity = 0.5
    shadowView.layer.shadowRadius = 5
    
    let view = MyView(frame: shadowView.bounds)
    view.backgroundColor = UIColor.white
    view.layer.cornerRadius = 10.0
    view.layer.borderColor = UIColor.gray.cgColor
    view.layer.borderWidth = 0.5
    view.clipsToBounds = true
    
    shadowView.addSubview(view)
    superview.addSubview(shadowView)
    

提交回复
热议问题