iOS-自定义UILable实现文本渐变色
//.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface SFYStrokeLabel : UILabel
/** 描多粗的边*/
@property (nonatomic, assign) NSInteger outLineWidth;
/** 外轮颜色*/
@property (nonatomic, strong) UIColor * outLinetextColor;
/** 里面字体默认颜色*/
@property (nonatomic, strong) UIColor * labelTextColor;
@end
//.m文件
#import "SFYStrokeLabel.h"
@implementation SFYStrokeLabel
- (void)drawRect:(CGRect)rect {
CGSize textSize = [self.text boundingRectWithSize:rect.size options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : self.font} context:nil].size;
CGFloat text_width = textSize.width;
CGFloat text_height = textSize.height;
CGContextRef context = UIGraphicsGetCurrentContext();
// 获取文字mask
[self.text drawInRect:self.bounds withAttributes:@{NSFontAttributeName : self.font}];
CGImageRef textMask = CGBitmapContextCreateImage(context);
// 清空画布
CGContextClearRect(context, rect);
// 添加描边
CGSize shadowOffset = self.shadowOffset;
CGContextSetLineWidth(context, self.outLineWidth);//字体边缘的宽度
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
self.textColor = [UIColor blackColor];//字体边缘加的颜色
[super drawTextInRect:rect];
CGContextSetTextDrawingMode(context, kCGTextStroke);
self.textColor = self.outLinetextColor;
self.shadowOffset = CGSizeMake(0, 10);
[super drawTextInRect:rect];
self.shadowOffset = shadowOffset;
// 设置蒙层
CGContextTranslateCTM(context, (rect.size.width-text_width)/2.0, self.bounds.size.height + self.bounds.size.height/2 - text_height/2);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, rect, textMask);
// 绘制渐变
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = {0,0.5,0.5,1};
CGFloat colors[] = {
0.5,0.0,0.4,1.0,
0.5,0.0,0.4,1.0,
1.0,0.0,0.0,1.0,
1.0,0.0,0.0,1.0
};
CGGradientRef gradient=CGGradientCreateWithColorComponents(colorSpace, colors, locations, 4);
CGPoint start = CGPointMake(0, self.bounds.size.height - text_height);
CGPoint end = CGPointMake(0, self.bounds.size.height);
CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation);
// 释放
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
//viewcontroller调用
SFYStrokeLabel* strokeLabel = [[SFYStrokeLabel alloc] initWithFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height / 2 - 100, [UIScreen mainScreen].bounds.size.width-40, 200)];
strokeLabel.textAlignment = NSTextAlignmentCenter;
strokeLabel.outLineWidth = 5;
strokeLabel.outLinetextColor = UIColor.systemGreenColor;
strokeLabel.text = @"❤️喜欢就点个关注吧👍";
strokeLabel.font = [UIFont systemFontOfSize:26 weight:UIFontWeightHeavy];
[self.view addSubview:strokeLabel];