先看效果
這里關鍵的地方在於鏤空文字的實現,可以用UILabel的drawRect方法。
.h文件
@interface HollowLabel : UILabel @end
.m文件
@interface HollowLabel(){ NSString *_labelText; UIFont *_labelFont; UIColor *_labelBackgroundColor; CGRect _labelRect; } @end
@implementation HollowLabel -(void)setText:(NSString *)text{ _labelText = text; } -(void)setFont:(UIFont *)font{ _labelFont = font; } -(void)setBackgroundColor:(UIColor *)backgroundColor{ _labelBackgroundColor = backgroundColor; } //重寫該方法,否則該方法會出問題
-(void)sizeToFit{ } //禁止使用該方法初始化
-(instancetype)init{ return nil; } -(instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { _labelRect = frame; } return self; }
重要的是drawRect的實現
-(void)drawRect:(CGRect)rect{ CGContextRef ctx = UIGraphicsGetCurrentContext(); [self drawHallowLabel:_labelText inRect:_labelRect inContext:ctx]; } -(void)drawHallowLabel:(NSString *)labText inRect:(CGRect )labrect inContext:(CGContextRef )context{ //記錄上下文的當前狀態
CGContextSaveGState(context); //設置混合色
CGContextSetBlendMode(context, kCGBlendModeDestinationOut); //lable上邊添加label
UILabel *lab = [[UILabel alloc]initWithFrame:labrect]; lab.text = labText; lab.backgroundColor = _labelBackgroundColor; lab.font = _labelFont; lab.textAlignment = NSTextAlignmentCenter; [lab.layer drawInContext:context]; //去除堆棧頂部的狀態,返回到之前的上下文狀態
CGContextRestoreGState(context); }
實現鏤空文字后,再在HollowLabel下貼圖,一層背景view,一層變色view,用NSTimer改變【變色view】的寬度就可以實現歌詞效果。