Skip to content

Instantly share code, notes, and snippets.

@d-ronnqvist
Created May 7, 2015 12:40
Show Gist options
  • Save d-ronnqvist/22f40a2f52f48ccf7e89 to your computer and use it in GitHub Desktop.
Save d-ronnqvist/22f40a2f52f48ccf7e89 to your computer and use it in GitHub Desktop.
Drawing a clipped gradient beyond the start and end points
import Foundation
import UIKit
class MyView: UIView {
override func drawRect(rect: CGRect) {
// just some path
let path = UIBezierPath(roundedRect: CGRectMake(10, 10, 200, 100), byRoundingCorners: .TopLeft | .BottomRight, cornerRadii: CGSizeMake(30, 60))
// fill with red
UIColor.redColor().setFill()
path.fill()
let ctx = UIGraphicsGetCurrentContext()
// the gradiend
let colors: NSArray = [UIColor.blueColor().CGColor, UIColor.greenColor().CGColor]
let colorSpace = CGBitmapContextGetColorSpace(ctx)
let locations: [CGFloat] = [0.2, 0.8]
let gradient = CGGradientCreateWithColors(colorSpace, colors, locations)
let options: CGGradientDrawingOptions = CGGradientDrawingOptions(kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation)
UIGraphicsPushContext(ctx)
// clip to the path
CGContextAddPath(ctx, path.CGPath)
CGContextClip(ctx)
CGContextDrawLinearGradient(ctx, gradient, CGPointMake(50, 0), CGPointMake(100, 100), options)
UIGraphicsPopContext()
}
}
let view = MyView(frame: CGRectMake(0, 0, 220, 120))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment