[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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容