views:

887

answers:

2

Does anyone know how to create a CGGradient that will fill my view,
my current code is this and it fill the UIView with a red rectangle I want to have a gradient (from black to gray for instance) instead of the rect :

- (void)drawRect:(CGRect)rect {
    CGContextRef context=UIGraphicsGetCurrentContext();
    CGRect r;
    r.origin.x=00.; r.origin.y=0.;
    r.size.width=rect.size.width; r.size.height=rect.size.height; 
    CGContextSetRGBFillColor(context, 1., 0., 0., 1.);
    CGContextFillRect (context,r); 
}

Thanks guyz ;)

+1  A: 

Use CGGradientCreateWithColorComponents or CGGradientCreateWithColors to create the gradient. (The latter takes CGColor objects.) Then, use CGContextDrawLinearGradient or CGContextDrawRadialGradient to draw it.

A linear gradient will extend infinitely in at least the two directions perpendicular to the line of the gradient. A radial gradient extends infinitely in every direction. To prevent the gradient from spilling outside your view, you'll probably need to add the view's bounds to the clipping path using CGContextClipToRect.

Peter Hosey
A: 

In my answer to this question, I provide code for drawing a gloss gradient within a UIView. The colors and drawing positions can be modified from that to form whatever linear gradient you need.

Brad Larson