iOS进阶

iOS-UILabel字体加边框和渐变色

2021-03-18  本文已影响0人  凉秋落尘

最近做了个需求,需要使用字体带边框和渐变色,显示效果如下:


image.png

主要方式,封装一个自定义UILabel代码,需要为字体加边框,并且需要设置丰富颜色,如果是数字可以使用多张图片切换,但是也可以写成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;

    // 设置蒙层
    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];
上一篇下一篇

猜你喜欢

热点阅读