Skip to content

Instantly share code, notes, and snippets.

@zarghol
Forked from M8Games/ShadowView.swift
Created December 5, 2016 14:14
Show Gist options
  • Save zarghol/4f539173211f23992cb70014646198a0 to your computer and use it in GitHub Desktop.
Save zarghol/4f539173211f23992cb70014646198a0 to your computer and use it in GitHub Desktop.
//
// ShadowView.swift
//
import UIKit
@IBDesignable
class ShadowView: UIView {
@IBInspectable var startAlpha: CGFloat = 90 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var midAlpha: CGFloat = 45 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var midPosPercent: CGFloat = 50 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var endAlpha: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
// let scaleFactor: CGFloat = 1
let rectangle = CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height)
ctx.saveGState()
ctx.addRect(rectangle)
ctx.clip()
let gradientColors: [CGFloat] = [ 0, 0, 0, self.startAlpha / 100,
0, 0, 0, self.midAlpha / 100,
0, 0, 0, self.endAlpha / 100 ]
let gradientLocations: [CGFloat] = [ 0, self.midPosPercent / 100, 0.9 ]
if let gradientRef = CGGradient(colorSpace: colorSpace, colorComponents: gradientColors, locations: gradientLocations, count: 3) {
let options: CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation]
ctx.drawLinearGradient(gradientRef, start: CGPoint.zero, end: CGPoint(x: 0, y: self.bounds.height), options: options)
}
// CGContextDrawLinearGradient( ctx, gradientRef, CGPoint(x: 0, y: 0), CGPoint(x: 0, y: self.bounds.height), CGGradientDrawingOptions(CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation) )
ctx.restoreGState()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment