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

前端 未结 2 1395
甜味超标
甜味超标 2020-12-31 20:14

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 im         


        
2条回答
  •  鱼传尺愫
    2020-12-31 21:05

    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);
    }
    

提交回复
热议问题