Skip to content

Instantly share code, notes, and snippets.

@milesegan
Created July 3, 2016 02:41
Show Gist options
  • Save milesegan/14ebd14925f37807e78029e5d5695d4d to your computer and use it in GitHub Desktop.
Save milesegan/14ebd14925f37807e78029e5d5695d4d to your computer and use it in GitHub Desktop.
// Adapted from http://blog.helftone.com/demystifying-inner-shadows-in-quartz/
import UIKit
class InnerShadowView: UIView {
var blurRadius = CGFloat(3) {
didSet { setNeedsDisplay() }
}
var offset = CGSize(width: 0, height: 2) {
didSet { setNeedsDisplay() }
}
var path = UIBezierPath() {
didSet { setNeedsDisplay() }
}
var shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5) {
didSet { setNeedsDisplay() }
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
backgroundColor = UIColor.clearColor()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextAddPath(context, path.CGPath)
CGContextClip(context)
let opaqueShadowColor = CGColorCreateCopyWithAlpha(shadowColor.CGColor, 1.0)
CGContextSetAlpha(context, CGColorGetAlpha(shadowColor.CGColor))
CGContextBeginTransparencyLayer(context, nil)
CGContextSetShadowWithColor(context, offset, blurRadius, opaqueShadowColor)
CGContextSetBlendMode(context, CGBlendMode.SourceOut)
CGContextSetFillColorWithColor(context, opaqueShadowColor)
CGContextAddPath(context, path.CGPath)
CGContextFillPath(context)
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment