Created
June 10, 2019 16:25
-
-
Save NeilsUltimateLab/4f894fe9df4ac468f2de52377c41ef2e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ShadowView: UIView { | |
var color: UIColor = .white { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var cornerRadius: CGFloat = 12 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowOpacity: Float = 0.4 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowRadius: CGFloat = 18 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowColor: UIColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowOffset: CGSize = .zero { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
private lazy var backgroundLayer: CAShapeLayer = { | |
let backgroundLayer = CAShapeLayer() | |
backgroundLayer.cornerRadius = cornerRadius | |
backgroundLayer.masksToBounds = true | |
return backgroundLayer | |
}() | |
private lazy var shadowLayer: CAShapeLayer = { | |
let shadowLayer = CAShapeLayer() | |
shadowLayer.fillColor = UIColor.clear.cgColor | |
return shadowLayer | |
}() | |
override func draw(_ rect: CGRect) { | |
super.draw(rect) | |
backgroundLayer.frame = rect | |
backgroundLayer.backgroundColor = color.cgColor | |
shadowLayer.frame = rect | |
shadowLayer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath | |
shadowLayer.shadowColor = shadowColor.cgColor | |
shadowLayer.shadowOffset = shadowOffset | |
shadowLayer.shadowOpacity = shadowOpacity | |
shadowLayer.shadowRadius = shadowRadius | |
self.layer.insertSublayer(shadowLayer, at: 0) | |
self.layer.insertSublayer(backgroundLayer, above: shadowLayer) | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
self.backgroundLayer.frame = self.bounds | |
self.shadowLayer.frame = self.bounds | |
shadowLayer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: cornerRadius).cgPath | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment