• 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 

  • 相关阅读:
    Fiddler捕获https请求时勾选了Decrypt HTTPS traffic还是获取不到证书的问题(转)
    ERROR: ORA-01033: ORACLE initialization or shutdown in progress Oracle无法启动的解决
    JavaScript数据类型、函数、对象
    HTML5新特性
    Java 操作XML,JDOM&DOM4J
    XML引入,DOM 方式解析XML 原理,SAX 方式解析XML
    Json引入键值key&value,数组,嵌套,用户注册
    Ajax异步XMLHttpRequest对象
    JavaScript基于对象引入,闭包,面向对象的实现
    MySql存储过程的操作
  • 原文地址:https://www.cnblogs.com/lyz0925/p/11778720.html
Copyright © 2020-2023  润新知