Created
May 7, 2015 12:40
-
-
Save d-ronnqvist/22f40a2f52f48ccf7e89 to your computer and use it in GitHub Desktop.
Drawing a clipped gradient beyond the start and end points
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 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