nambar
nambar

Reputation: 573

iOS draw gradient in part of the view

I've created a custom progress bar which subclass UIView and implements drawRect. I manage to draw a single gradient on the entire view. I'd like however to draw several different gradients, each one in a different position. How to I limit CGContextDrawLinearGradient to smaller rect inside my view?

glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGPoint topCenter = CGPointMake(start + (CGRectGetMidX(currentBounds)/currentBounds.size.width), 0.0f);`
        CGPoint midCenter = CGPointMake(start + (CGRectGetMidX(currentBounds)/currentBounds.size.width), currentBounds.size.height);
        CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
        start = start + (values[i] / currentBounds.size.width);
        CGGradientRelease(glossGradient);
    }

Upvotes: 1

Views: 3017

Answers (2)

mrueg
mrueg

Reputation: 8225

You can use CGContectClipToRect to restrict the drawing area

Then for each gradient do:

CGContextSaveGState(currentContext);
CGContextClipToRect(theRect); // theRect should be the area where you want to draw the gradient
... // gradient drawing code
CGContextRestoreGState(currentContext);

Upvotes: 4

rob mayoff
rob mayoff

Reputation: 386018

As stated in Quartz 2D Programming Guide:

When you paint a gradient, Quartz fills the current context. Painting a gradient is different from working with colors and patterns, which are used to stroke and fill path objects. As a result, if you want your gradient to appear in a particular shape, you need to clip the context accordingly.

Since you want to draw each gradient in a rectangle, you will want to do something like this for each gradient and rectangle:

CGContextSaveGState(currentContext); {
    CGContextClipToRect(currentContext, currentBounds);
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
} CGContextRestoreGState(currentContext);

Upvotes: 3

Related Questions