Created
March 23, 2019 08:07
-
-
Save NeilsUltimateLab/d83184e64d63b784b5a29e0c15f7bb95 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
import UIKit | |
class ShadowView: UIView { | |
var color: UIColor? { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var cornerRadius: CGFloat = 16 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowOpacity: Float = 0.4 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowRadius: CGFloat = 16 { | |
didSet { | |
self.setNeedsDisplay() | |
} | |
} | |
var shadowColor: UIColor = .black { | |
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) | |
self.backgroundColor = UIColor.clear | |
backgroundLayer.frame = rect | |
backgroundLayer.backgroundColor = color?.cgColor | |
shadowLayer.frame = rect | |
shadowLayer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath | |
shadowLayer.shadowColor = shadowColor.cgColor | |
shadowLayer.shadowOffset = CGSize(width: 0, height: 0) | |
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