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

前端 未结 2 1396
甜味超标
甜味超标 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:00

    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]];
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题