[iOS] 字体渐变色

接到给文字加渐变色的需求后,我和同事一筹莫展,在网上找各种资料,找到两种实现方式:
1、通过把label的layer做为一个渐变图层的mask,即只让文字部分遮住渐变图层

    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = self.view.bounds;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:20];
    label.numberOfLines = 0;
    label.text = @"炫彩字体 炫彩字体 炫彩字体 炫彩字体 炫彩字体 炫彩字体";
    [self.view addSubview:label];

    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    layer.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor];
    layer.startPoint = CGPointZero;
    layer.endPoint = CGPointMake(1, 1);
    layer.frame = label.bounds;
    layer.mask = label.layer; //把文字作为渐变图层的遮罩
    [self.view.layer addSublayer:layer];

2、重写UILabel的绘制方法drawTextInRect:,从上下文生成图片,清除上下文内容,再把图片作为整个上下文的mask,最后在上下文里绘制渐变

    [super drawTextInRect:rect]; //先绘制
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat width = rect.size.width;
    CGFloat height = rect.size.height;
    CGImageRef imageRef = CGBitmapContextCreateImage(context);//获得倒置的图片
    CGContextClearRect(context, rect); //清除内容
    CGContextTranslateCTM(context, 0, height); // 坐标转换
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CGContextClipToMask(context, rect, imageRef);//将图片设置为mark
    //划渐变色图层
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef, (__bridge CFArrayRef)gradientColors, NULL);
    CGPoint startPoint = CGPointZero;
    CGPoint endPoint = CGPointMake(width, height);;
    CGContextDrawLinearGradient(context, gradientRef, startPoint, endPoint,  kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(imageRef);
    CGGradientRelease(gradientRef);

毕竟是消息列表,就选择了性能稍微好点的第二种方式。万事大吉,炫彩字体就出来了。


image.png

但是后来发现如果文字中有表情,表情就成为了一个圆形色块,仔细一想应该是把表情的轮廓作为遮罩处理的。


image.png

怎么让表情不作为渐变色的遮罩呢,只想到一个方法,用CoreText绘制。先把当前上下文环境保存起来。首先只绘制普通文字,遇到表情,把表情的位置预留出来,并把表情和其位置信息保存起来供下次绘制。绘制完文字后,取到图片、清除上下文、坐标转换、设置mask,然后绘制渐变。然后恢复之前保存的上下文环境,并取到表情信息再一次绘制表情。

>   CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context); //保存上下文环境
    NSDictionary *attributes = @{NSFontAttributeName:self.font, NSForegroundColorAttributeName:self.textColor};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.text attributes:attributes];
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);
    //生成CTFrame
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
    CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, width, height), NULL);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil);
    CFArrayRef CTLines = CTFrameGetLines(frameRef); //获取到每一行
    NSInteger lineCount = CFArrayGetCount(CTLines);
    // 绘制每一行的普通文字
    CGFloat lineTop = 0;
    NSMutableArray *emojis = [NSMutableArray array];
    for (NSInteger i = 0; i < lineCount; i++) {
        CTLineRef line = CFArrayGetValueAtIndex(CTLines, i);
        CGFloat ascent, descent, leading;
        CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
        CGFloat runHeight = ascent + fabs(descent) + fabs(leading);
        NSArray *runArray = (__bridge NSArray *)CTLineGetGlyphRuns(line); //获取到每一个glyphRun
        CGFloat startX = 0;
        for (NSInteger j = 0; j< runArray.count; j++) {
            CTRunRef runRef = (__bridge  CTRunRef)runArray[j];
            CFRange runRange = CTRunGetStringRange(runRef);
            NSDictionary * attributes = (NSDictionary *)CTRunGetAttributes(runRef);
            UIFont *font = [attributes objectForKey:@"NSFont"];
            CGFloat runWidth = CTRunGetTypographicBounds(runRef, CFRangeMake(0, 0), 0, 0, 0);
            NSString *str = [self.text substringWithRange:NSMakeRange(runRange.location, runRange.length)];
            if ([font.familyName containsString:@"Emoji"]) { //判断是否是emoji表情
                CGRect temRect = CGRectMake(startX,lineTop, runWidth, runHeight);
                [emojis addObject:@{@"str":str, @"rect":[NSValue valueWithCGRect:temRect]}];
            } else {
//这里不加上descent/2,文字会往上偏,这里还不清楚为什么,有大佬给指教下吗
                CGRect temRect = CGRectMake(startX,lineTop + descent/2, runWidth, runHeight);
                [str drawInRect:temRect withAttributes:attributes];
            }
             startX +=runWidth;
        }
        lineTop += runHeight;
    }
    //释放资源
    CFRelease(framesetter);
    CFRelease(frameRef);
    CGPathRelease(path);
    //获取图片
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    CGContextClearRect(context, rect);
    //坐标转换
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);
    //将图片设置为mark
    CGContextClipToMask(context, rect, imageRef);
    //绘制渐变层
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef, (__bridge CFArrayRef)gradientColors, NULL);
    CGPoint startPoint = CGPointZero;
    CGPoint endPoint = CGPointMake(width, height);
    CGContextDrawLinearGradient(context, gradientRef, startPoint, endPoint,  kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    //释放资源
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(imageRef);
    CGGradientRelease(gradientRef);
    //恢复上下文环境
    CGContextRestoreGState(context);
    //绘制表情
    for (NSDictionary *emoji in emojis) {
        NSString *str = emoji[@"str"];
        CGRect rect = [emoji[@"rect"] CGRectValue];
        [str drawInRect:rect withAttributes:attributes];
    }

由于对CoreText了解有限,实现的也很蹩脚,不过总算能够满足效果了。

重点:后来,同事突然给我说,有一个更简单且完美的方法,直接设置textColor为渐变颜色就行了。

    UIGraphicsBeginImageContextWithOptions(label.bounds.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //绘制渐变层
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef,
                                                           (__bridge CFArrayRef)@[(id)[UIColor redColor].CGColor,(id)[UIColor greenColor].CGColor],
                                                           NULL);
    CGPoint startPoint = CGPointZero;
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(label.bounds), CGRectGetMaxY(label.bounds));
    CGContextDrawLinearGradient(context, gradientRef, startPoint, endPoint,  kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    //取到渐变图片
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    //释放资源
    CGColorSpaceRelease(colorSpaceRef);
    CGGradientRelease(gradientRef);
    UIGraphicsEndImageContext();
    label.textColor = [UIColor colorWithPatternImage:gradientImage];
image.png

你可能感兴趣的:([iOS] 字体渐变色)