文字渐变色的类:
头文件:
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GradientLabel : UILabel
@property(nonatomic, strong) NSArray* colors;
@end
NS_ASSUME_NONNULL_END
实现文件:
#import "GradientLabel.h"
@implementation GradientLabel
- (void)drawRect:(CGRect)rect
{
CGSize textSize = [self.text sizeWithAttributes:@{NSFontAttributeName : self.font}];
CGRect textRect = (CGRect){0, 0, textSize};
// 画文字(不做显示用 主要作用是设置layer的mask)
CGContextRef context = UIGraphicsGetCurrentContext();
[self.textColor set];
[self.text drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font} context:NULL];
// 坐标 (只对设置后的画到context起作用 之前画的文字不起作用)
CGContextTranslateCTM(context, 0.0f, rect.size.height- (rect.size.height - textSize.height)*0.5);
CGContextScaleCTM(context, 1.0f, -1.0f);
CGImageRef alphaMask = NULL;
alphaMask = CGBitmapContextCreateImage(context);
CGContextClearRect(context, rect);// 清除之前画的文字
// 设置mask
CGContextClipToMask(context, rect, alphaMask);
// 画渐变色
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)self.colors, NULL);
CGPoint startPoint = CGPointMake(textRect.origin.x,
textRect.origin.y);
CGPoint endPoint = CGPointMake(textRect.origin.x + textRect.size.width,
textRect.origin.y + textRect.size.height);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
// 释放内存
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
CFRelease(alphaMask);
}
@end
要实现文字渐变的类中:
1. 导入头文件:
#import "GradientLabel.h"
2. 添加属性:
@property(strong, nonatomic) GradientLabel *label;
3. 实现文字渐变色(修改代码中橙色的十六进制颜色即可):
// 两色渐变
self.label.colors = @[(id)ColorHex(0xAAAAAA).CGColor, (id)ColorHex(0xBBBBBB).CGColor];
// 三色渐变
self.label.colors = @[(id)ColorHex(0xCCCCCC).CGColor, (id)ColorHex(0xDDDDDD).CGColor, (id)ColorHex(0xEEEEEE).CGColor];