windson
windson

Reputation: 667

Creating a gradient fill for text using [UIColor colorWithPatternImage:]

I want to create a gradient for the fill color of my text. Currently I am doing it by setting the color of a UILabel's text as

UIImage *image = [UIImage imageNamed:@"GradientFillImage.png"];
myLabel.textColor = [UIColor colorWithPatternImage:image];

Where GradientFillImage.png is a simple image file with a linear gradient painted on it.

This works fine until I want to resize the font. Since the image file is of constant dimensions and does not resize when I resize the font, the gradient fill for the font gets messed up. How do I create a custom size pattern image and apply it as a fill pattern for text?

Upvotes: 7

Views: 6395

Answers (2)

bigkm
bigkm

Reputation: 2277

I've just finished a UIColor class extension that makes this a 1 line + block thing.

https://github.com/bigkm/UIColor-BlockPattern

CGRect rect = CGRectMake(0.0,0.0,10.0,10.0);

[UIColor colorPatternWithSize:rect.size andDrawingBlock:[[^(CGContextRef c) {
    UIImage *image = [UIImage imageNamed:@"FontGradientPink.png"];
    CGContextDrawImage(context, rect, [image CGImage]);
} copy] autorelease]];

Upvotes: 4

windson
windson

Reputation: 667

Ok, I figured it out. Basically, we can override drawRectInText and use our own pattern to color the fill. The advantage of doing this is that we can resize the image into our pattern frame.

First we create a CGPattern object and define a callback to draw the pattern. We also pass the size of the label as a parameter in the callback. We then use the pattern that is drawn in the callback and set it as the fill color of the text:

- (void)drawTextInRect:(CGRect)rect
{
    //set gradient as a pattern fill
    CGRect info[1] = {rect};
    static const CGPatternCallbacks callbacks = {0, &drawImagePattern, NULL};
    CGAffineTransform transform = CGAffineTransformMakeScale(1.0, -1.0);

    CGPatternRef pattern = CGPatternCreate((void *) info, rect, transform, 10.0, rect.size.height, kCGPatternTilingConstantSpacing, true, &callbacks);
    CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);
    CGFloat alpha = 1.0;
    CGColorRef patternColorRef = CGColorCreateWithPattern(patternSpace, pattern, &alpha);
    CGColorSpaceRelease(patternSpace);
    CGPatternRelease(pattern);
    self.textColor = [UIColor colorWithCGColor:patternColorRef];
    self.shadowOffset = CGSizeZero;
    [super drawTextInRect:rect];
}

The callback draws the image into the context. The image is resized as per the frame size that is passed into the callback.

void drawImagePattern(void *info, CGContextRef context)
{
    UIImage *image = [UIImage imageNamed:@"FontGradientPink.png"];
    CGImageRef imageRef = [image CGImage];
    CGRect *rect = info;
    CGContextDrawImage(context, rect[0], imageRef);
}

Upvotes: 2

Related Questions