iOS 添加自定义字体、仿开机解锁的文字闪烁

最近项目需要用自己的字体,针对这个做一个记录。首先我们拿到字体库


比如这个格式的

1、先将字体库拖入到项目中,然后到 Target - Build Phases下,在下图中的两个地方将字体库文件进行添加(如果没有就添加上)


添加文件

2、去 Info.plist 中添加键值对,记住值一定是指定格式,就比如下图这个,需要将.tff也要加上(Fonts provided by application - 键)这里如果有多个字体就添加多个item.


添加键值

3、寻找字体库的特有名称,新加入字体库的名称并不一定是字体的名称,所以我们要确定真实的字体名称
(1)可以按照我这种方法,右键显示简介,查看全名,如下图


查看字体库名称

(2)第二种就是双击字体,安装在mac上,然后打开字体册进行查看


查看字体库名称

(3)第三种方法就是通过代码,将字体打印出来,去找你所安装的字体库,我没使用这种,找起来太慢了。
//    遍历所有字体
    NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
    NSArray *fontNames;
    NSInteger indFamily, indFont;
    for (indFamily=0; indFamily<familyNames.count; indFamily++)
    {
        NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
        fontNames = [[NSArray alloc] initWithArray:
                     [UIFont fontNamesForFamilyName:
                      [familyNames objectAtIndex:indFamily]]];
        for (indFont=0; indFont<[fontNames count]; ++indFont)
        {
            NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
        }
    }

4、怎么使用,如下:

    self.label.font = [UIFont fontWithName:@"Post No Bills Colombo ExtraBold" size:22.0f];

添加字体库到这里就结束了.....

接下来讲一下文字闪烁的实现

1、首先创建一个继承UILable的类,方便后续使用,.h代码如下:

#import <UIKit/UIKit.h>

/** 拥有光晕扫过效果的Label */
@interface CLHaloLabel : UILabel

/** 光晕循环一次的持续时间,默认循环时间为3秒 */
@property (nonatomic, assign) CGFloat haloDuration;
/** 光晕宽度占Label宽度的百分比,默认0.5 */
@property (nonatomic, assign) CGFloat haloWidth;
/** 光晕颜色,默认白色 */
@property (nonatomic, strong) UIColor *haloColor;
/** 是否执行动画,默认为NO */
@property (nonatomic, assign, getter = isAnimated) BOOL animated;

@end

.m代码如下

#import "CLHaloLabel.h"
#import <CoreText/CoreText.h>


/** 默认光晕循环一次的持续时间 */
static const NSTimeInterval kHaloDuration = 3;

/** 默认光晕宽度 */
static const CGFloat kHaloWidth = 0.5f;

/** 默认光晕颜色 */
#define kHaloColor  [UIColor whiteColor]

/** 光晕动画ID */
static NSString *const kAnimationKey = @"CLHaloLabelAnimation";



@interface CLHaloLabel ()

/** 文字层 */
@property (nonatomic, strong) CATextLayer *textLayer;

/** 动画步调 */
@property (nonatomic, copy) NSString *animationPacing;

/** 动画步调可选的选项
kCAMediaTimingFunctionLinear    // 线性动画
kCAMediaTimingFunctionEaseIn    // 快速进入动画
kCAMediaTimingFunctionEaseOut   // 快速出来动画
kCAMediaTimingFunctionEaseInEaseOut // 快速进入出来动画
kCAMediaTimingFunctionDefault   // 默认动画是curve动画,也就是曲线动画
*/

@end



@implementation CLHaloLabel

@synthesize animated = _animated;


#pragma mark - 初始化

/** 初始化方法,用于从代码中创建的类实例 */
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [self defaultInit];
    }
    return self;
}

/** 初始化方法,用于从代码中创建的类实例 */
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self defaultInit];
    }
    return self;
}

/** 初始化方法,用于从xib文件中载入的类实例 */
- (instancetype)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self)
    {
        [self defaultInit];
    }
    return self;
}

/** 默认的初始化方法 */
- (void)defaultInit
{
    // 设置默认的光晕颜色、光晕持续时间、光晕宽度
    _haloColor    = kHaloColor;
    _haloDuration = kHaloDuration;
    _haloWidth    = kHaloWidth;
    _animationPacing = kCAMediaTimingFunctionEaseInEaseOut;
    
    // 设置渐变层参数
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    gradientLayer.backgroundColor  = [super.textColor CGColor];
    gradientLayer.startPoint       = CGPointMake(-_haloWidth, 0);
    gradientLayer.endPoint         = CGPointMake(0, 0);
    gradientLayer.colors           = @[(id)[self.textColor CGColor],
                                       (id)[self.haloColor CGColor],
                                       (id)[self.textColor CGColor]];
    
    // 设置文字层参数
    self.textLayer                    = [CATextLayer layer];
    self.textLayer.backgroundColor    = [[UIColor clearColor] CGColor];
    self.textLayer.contentsScale      = [[UIScreen mainScreen] scale];
    self.textLayer.rasterizationScale = [[UIScreen mainScreen] scale];
    self.textLayer.frame              = self.bounds;
    self.textLayer.anchorPoint        = CGPointZero;
    
    // 设置Label参数,针对从xib文件中载入的Label,需要调用self的属性设置方法
    [self setFont:          super.font];
    [self setTextAlignment: super.textAlignment];
    [self setText:          super.text];
    [self setTextColor:     super.textColor];
    
    // 将文字层作为蒙层,覆盖到渐变层上
    gradientLayer.mask = self.textLayer;
    
    // 开启动画
    self.animated = YES;
}


#pragma mark - 重载类方法

/** 重写Label的layer为渐变层 */
+ (Class)layerClass
{
    return [CAGradientLayer class];
}

/** 停止重绘,使用文字层绘制 */
- (void)drawRect:(CGRect)rect {}


#pragma mark - 布局子层

- (void)layoutSublayersOfLayer:(CALayer *)layer
{
    [super layoutSublayersOfLayer:layer];
    self.textLayer.frame = self.layer.bounds;
}


#pragma mark - 属性

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self setNeedsDisplay];
}

/** 光晕持续时间 */
- (void)setHaloDuration:(CGFloat)haloDuration
{
    _haloDuration = haloDuration;
    if(_animated)
    {
        [self stopAnimating];
        [self startAnimating];
    }
}

/** 光晕宽度 */
- (void)setHaloWidth:(CGFloat)haloWidth
{
    _haloWidth = haloWidth;
    
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    gradientLayer.startPoint       = CGPointMake(-_haloWidth, 0);
    
    if(_animated)
    {
        [self stopAnimating];
        [self startAnimating];
    }
}

/** 文字颜色 */
- (UIColor *)textColor
{
    // 文字颜色为渐变层背景色
    UIColor *textColor = [UIColor colorWithCGColor:self.layer.backgroundColor];
    if (!textColor)
    {
        textColor = [super textColor];
    }
    return textColor;
}

- (void)setTextColor:(UIColor *)textColor
{
    UIColor *haloColor = self.haloColor ? self.haloColor : kHaloColor;
    
    // 重设渐变层背景色和渐变层颜色表
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    gradientLayer.backgroundColor  = [textColor CGColor];
    gradientLayer.colors           = @[(id)[textColor CGColor],
                                       (id)[haloColor CGColor],
                                       (id)[textColor CGColor]];
    
    [self setNeedsDisplay];
}

/** 文字 */
- (NSString *)text
{
    // 返回文字层文字
    return self.textLayer.string;
}

- (void)setText:(NSString *)text
{
    self.textLayer.string = text;
    [self setNeedsDisplay];
}

/** 文字字体 */
- (UIFont *)font
{
    CTFontRef ctFont    = self.textLayer.font;
    NSString *fontName  = (__bridge_transfer NSString *)CTFontCopyName(ctFont, kCTFontPostScriptNameKey);
    CGFloat fontSize    = CTFontGetSize(ctFont);
    return [UIFont fontWithName:fontName size:fontSize];
}

- (void)setFont:(UIFont *)font
{
    CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)(font.fontName), font.pointSize, &CGAffineTransformIdentity);
    self.textLayer.font = fontRef;
    self.textLayer.fontSize = font.pointSize;
    CFRelease(fontRef);
    [self setNeedsDisplay];
}

/** 文字对齐方式 */
- (NSTextAlignment)textAlignment
{
    return [self.class UITextAlignmentFromCAAlignment:self.textLayer.alignmentMode];
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
    self.textLayer.alignmentMode = [self.class CAAlignmentFromUITextAlignment:textAlignment];
}

+ (NSString *)CAAlignmentFromUITextAlignment:(NSTextAlignment)textAlignment
{
    switch (textAlignment) {
        case NSTextAlignmentLeft:   return kCAAlignmentLeft;
        case NSTextAlignmentCenter: return kCAAlignmentCenter;
        case NSTextAlignmentRight:  return kCAAlignmentRight;
        default:                    return kCAAlignmentNatural;
    }
}

+ (NSTextAlignment)UITextAlignmentFromCAAlignment:(NSString *)alignment
{
    if ([alignment isEqualToString:kCAAlignmentLeft])       return NSTextAlignmentLeft;
    if ([alignment isEqualToString:kCAAlignmentCenter])     return NSTextAlignmentCenter;
    if ([alignment isEqualToString:kCAAlignmentRight])      return NSTextAlignmentRight;
    if ([alignment isEqualToString:kCAAlignmentNatural])    return NSTextAlignmentLeft;
    return NSTextAlignmentLeft;
}


#pragma mark - 光晕动画

- (BOOL) isAnimated
{
    return _animated;
}

- (void) setAnimated:(BOOL)animated
{
    _animated = animated;
    if (_animated)
        [self startAnimating];
    else
        [self stopAnimating];
}

- (void)setHaloColor:(UIColor *)haloColor
{
    _haloColor = haloColor;
    
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    gradientLayer.colors           = @[(id)[self.textColor CGColor],
                                       (id)[self.haloColor CGColor],
                                       (id)[self.textColor CGColor]];
    [self setNeedsDisplay];
}

/** 开启动画 */
- (void)startAnimating
{
    static NSString *gradientStartPointKey = @"startPoint";
    static NSString *gradientEndPointKey = @"endPoint";
    
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    if([gradientLayer animationForKey:kAnimationKey] == nil)
    {
        // 通过不断改变渐变的起止范围,来实现光晕效果
        CABasicAnimation *startPointAnimation = [CABasicAnimation animationWithKeyPath:gradientStartPointKey];
        startPointAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(1.0, 0)];
        startPointAnimation.timingFunction = [CAMediaTimingFunction functionWithName:_animationPacing];
        
        CABasicAnimation *endPointAnimation = [CABasicAnimation animationWithKeyPath:gradientEndPointKey];
        endPointAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(1 + _haloWidth, 0)];
        endPointAnimation.timingFunction = [CAMediaTimingFunction functionWithName:_animationPacing];
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.animations = @[startPointAnimation, endPointAnimation];
        group.duration = _haloDuration;
        group.timingFunction = [CAMediaTimingFunction functionWithName:_animationPacing];
        group.repeatCount = HUGE_VALF;
        
        [gradientLayer addAnimation:group forKey:kAnimationKey];
    }
}

/** 结束动画 */
- (void)stopAnimating
{
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    if([gradientLayer animationForKey:kAnimationKey])
        [gradientLayer removeAnimationForKey:kAnimationKey];
}

2、具体怎么使用呢

//    @property (weak, nonatomic) IBOutlet CLHaloLabel *nameL;// 闪烁文字
    self.nameL.text = @"开机解锁";
    self.nameL.textColor = [UIColor whiteColor];
    self.nameL.haloColor = [UIColor blackColor];
    self.nameL.textAlignment = NSTextAlignmentCenter;
    self.nameL.font = [UIFont systemFontOfSize:22];
    self.nameL.animated = YES;

哦了,到这里基本就完工了。附上demo地址,有需要进行下载。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容