最近做了個需求滚躯,需要使用字體帶邊框和漸變色,顯示效果如下:
主要方式柳畔,封裝一個自定義UILabel代碼馍管,需要為字體加邊框,并且需要設(shè)置豐富顏色薪韩,如果是數(shù)字可以使用多張圖片切換确沸,但是也可以寫成UIlabel比較通用性,代碼如下:
@interface StrokeLabel : UILabel
/** 描多粗的邊*/
@property (nonatomic, assign) NSInteger outLineWidth;
/** 外輪顏色*/
@property (nonatomic, strong) UIColor *outLinetextColor;
/** 里面字體默認顏色*/
@property (nonatomic, strong) UIColor *labelTextColor;
@end
@implementation StrokeLabel
- (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;
// 設(shè)置蒙層
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);
}
@end
自定義控件使用方法如下:
self.strokeLabel = [[StrokeLabel alloc] initWithFrame:CGRectMake(20, 250, 300, 100)];
self.strokeLabel.textAlignment = NSTextAlignmentCenter;
self.strokeLabel.outLineWidth = 5;
self.strokeLabel.outLinetextColor = UIColor.systemGreenColor;
self.strokeLabel.text = @"1234567890";
self.strokeLabel.font = [UIFont systemFontOfSize:40 weight:UIFontWeightHeavy];
[self.view addSubview:self.strokeLabel];