OC-类似歌词字体颜色逐字变化的实现方法

 

预期实效果图如下:

 

 

如上图所示,文字的颜色会根据时间的移动,逐字变成绿色。

 

实现方法:
(1)调用方法:

  用 void UIRectFillUsingBlendMode(CGRect rect, CGBlendMode blendMode) 这个方法来实现

(2)实现逻辑:

  自定义Label,通过label的drawRect:方法 获取Label的图形上下文,使用调用UIRectFillUsingBlendMode:混合填充的方式来实现label颜色的绘制

(3)代码实现:

  创建自定义的label:

  .h 和.m的文件如下:

----------------.h--------------------
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface YALabel : UILabel

@property (nonatomic, assign) CGFloat progress ;

@end


----------------.m--------------------

#import "YALabel.h"

@implementation YALabel


- (void)drawRect:(CGRect)rect {
    
    [super drawRect:rect];

    [[UIColor greenColor] set]; // 填充
    
  // 这个rect的x、y、width、height 可根据自己的需求设置 rect = CGRectMake(rect.size.width *self.progress - 20, rect.origin.y, 40, rect.size.height); UIRectFillUsingBlendMode(rect, kCGBlendModeSourceIn); } - (void)setProgress:(CGFloat)progress { _progress = progress; [self setNeedsDisplay]; }

 

  调用:

#import "ViewController.h"

#import "YALabel.h"

@interface ViewController ()

@property (nonatomic,strong) YALabel * yaLabl ;

@property (nonatomic,assign) CGFloat progress ;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.yaLabl = [[YALabel alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width - 20, 30)];

    self.yaLabl.text = @"叶绿不同赏,叶黄不同悲;若问相思处,叶绿叶黄时~~~~~~~";
    self.yaLabl.textColor = [UIColor blackColor];
    self.yaLabl.font = [UIFont systemFontOfSize:18];
    
    [self.view addSubview:self.yaLabl];
    
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
    
    self.progress = 0.0;

}

- (void)update {
    if (self.progress >= 1.0) {
        self.progress = 0.0;
    }
    self.progress += 0.01;
    self.yaLabl.progress = self.progress;
}

 (4)注意事项:

  label不能设置背景色,如果设置了背景色,那么这个绘制的方式,是给label的背景色绘制,而不是给label的文字绘制颜色;

  下图是我添加了label的背景色后的效果:

(5)CGBlandMode参数为一个枚举类型,以及 每个枚举值的计算公式,提供一个参考链接,有兴趣就看看:

  https://www.jianshu.com/p/96cfd3697b21 

 

posted @ 2019-11-01 18:49  一人前行  阅读(431)  评论(0编辑  收藏  举报