Skip to content

Instantly share code, notes, and snippets.

@chrismiles
Created August 7, 2014 12:02
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrismiles/e7e10c768532164159e4 to your computer and use it in GitHub Desktop.
Save chrismiles/e7e10c768532164159e4 to your computer and use it in GitHub Desktop.
Core Graphics gradient drawing with Swift? No problem.
let colorSpace = CGColorSpaceCreateDeviceRGB()
let componentCount : UInt = 4
let components : [CGFloat] = [
0, 0, 0, 0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
0, 0, 0, 0
]
let locations : [CGFloat] = [0, 0.25, 0.75, 1.0]
let gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, componentCount)
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: CGRectGetWidth(bounds), y: 0)
CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0)
@leeprobert
Copy link

// Swift 2 update:
let context = UIGraphicsGetCurrentContext() // <-- and you missed the context
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, CGGradientDrawingOptions(rawValue: 0))

/*
Have been struggling with this for too long. Going to buy Paintcode instead!
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment