Reputation: 11645
I try to draw a gradient in a rectangle. Following picture shows, that gradient in general works (blue), but it fills the entire screen.
I like to do the gradient only in a specific area like the green rectangle.
How can I do this ?
My code for the gradient experiment :-)
let context = UIGraphicsGetCurrentContext()
//let locations: [CGFloat] = [ 0.0, 0.25, 0.5, 0.75 ]
let locations: [CGFloat] = [ 0.0, 0.99 ]
let colors = [UIColor.blueColor().CGColor,
UIColor.whiteColor().CGColor]
let colorspace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(colorspace,
colors, locations)
var startPoint = CGPoint()
var endPoint = CGPoint()
startPoint.x = 0.0
startPoint.y = 10.0
endPoint.x = self.frame.width-100;
endPoint.y = 10
//let rectangle_main = CGRectMake(CGFloat(15), CGFloat(0), CGFloat(1000), CGFloat(30));
//CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
Upvotes: 2
Views: 2413
Reputation: 23078
You need to specify a clipping path right before drawing the gradient.
In your case, create a rectangle path and call CGContextClip(context)
CGContextAddRect(context, CGRect(...))
CGContextClip(context)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
The gradient will be clipped to the rectangle.
Upvotes: 4