-
-
Save llinardos/d1ede3b491efc8edac940c5ea8631c6f to your computer and use it in GitHub Desktop.
This file contains 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 | |
import PlaygroundSupport | |
public class ShadowView: UIView { | |
var offset: CGSize = CGSize(width: 0, height: 0) | |
var radius: CGFloat = 10 | |
var opacity: Float = 0.5 | |
var color: UIColor = UIColor.black | |
var cornerRadius: Float = 0.0 | |
var isCircle: Bool = false | |
var showOnlyOutsideBounds: Bool = true | |
override public func layoutSubviews() { | |
super.layoutSubviews() | |
var cornerRadius = self.cornerRadius | |
if isCircle { | |
cornerRadius = Float(min(frame.height, frame.width) / 2.0) | |
} | |
if showOnlyOutsideBounds { | |
let maskLayer = CAShapeLayer() | |
let path = CGMutablePath() | |
path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets.zero), cornerRadius: CGFloat(cornerRadius)).cgPath) | |
path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets(top: -offset.height - radius*2, left: -offset.width - radius*2, bottom: -offset.height - radius*2, right: -offset.width - radius*2)), cornerRadius: CGFloat(cornerRadius)).cgPath) | |
maskLayer.backgroundColor = UIColor.black.cgColor | |
maskLayer.path = path; | |
maskLayer.fillRule = .evenOdd | |
self.layer.mask = maskLayer | |
} else { | |
self.layer.masksToBounds = false | |
} | |
self.layer.shadowOffset = self.offset | |
self.layer.shadowRadius = self.radius | |
self.layer.shadowOpacity = self.opacity | |
self.layer.shadowColor = self.color.cgColor | |
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: CGFloat(cornerRadius)).cgPath | |
} | |
} | |
class DemoView : UIView { | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
let gradient = CAGradientLayer() | |
gradient.colors = [ | |
UIColor(red: 87.0/255.0, green: 247.0/255.0, blue: 141.0/255.0, alpha: 1.0).cgColor, | |
UIColor(red: 31/255.0, green: 148.0/255.0, blue: 151.0/255.0, alpha: 1.0).cgColor | |
] | |
gradient.frame = self.bounds | |
self.layer.addSublayer(gradient) | |
let label = UILabel() | |
label.frame = CGRect(x: 100, y: 130, width: 100, height: 40) | |
label.text = "Hello World!" | |
label.textColor = .black | |
label.textAlignment = .center | |
self.addSubview(label) | |
let shadow = ShadowView(frame: label.frame) | |
self.addSubview(shadow) | |
} | |
required init?(coder aDecoder: NSCoder) { return nil } | |
} | |
// Present the view controller in the Live View window | |
PlaygroundPage.current.liveView = DemoView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment