iOS梯度动画

效果图

PJAnimatedMaskLabel.gif

代码

设置梯度条

- (void)didMoveToWindow {
    
    [self.layer addSublayer:_gradientLayer];
    
    CABasicAnimation *gradientAnimation = [CABasicAnimation animationWithKeyPath:@"locations"];
    gradientAnimation.fromValue = @[@0.0, @0.0, @0.25];
    gradientAnimation.toValue = @[@0.75, @1.0, @1.0];
    gradientAnimation.duration = 3.0;
    gradientAnimation.repeatCount = CGFLOAT_MAX;
    [_gradientLayer addAnimation:gradientAnimation forKey:nil];
}

- (void)setupUI {
    
    _gradientLayer = [CAGradientLayer layer];
    _gradientLayer.colors = @[(id)[UIColor blackColor].CGColor,
                              (id)[UIColor whiteColor].CGColor,
                              (id)[UIColor blackColor].CGColor];
    _gradientLayer.locations = @[@0.25, @0.5, @0.75];
    _gradientLayer.startPoint = CGPointMake(0.0, 0.5);
    _gradientLayer.endPoint = CGPointMake(1.0, 0.5);
}
MaskLabel.gif

设置显示区域

- (void)layoutSubviews {
    
    [super layoutSubviews];
    _gradientLayer.frame = CGRectMake(-self.bounds.size.width,
                                      self.bounds.origin.y,
                                      3 * self.bounds.size.width,
                                      self.bounds.size.height);
}

设置文字

- (void)setText:(NSString *)text withFontSize:(CGFloat)size {
    
    [self setNeedsDisplay];
    
    NSMutableDictionary *textAttributes = [NSMutableDictionary dictionary];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:size];
    
    textAttributes[NSParagraphStyleAttributeName] = style;
    textAttributes[NSFontAttributeName] = font;
    
    UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0);
    [text drawInRect:self.bounds withAttributes:textAttributes];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CALayer *maskLayer = [CALayer layer];
    maskLayer.backgroundColor = [UIColor clearColor].CGColor;
    maskLayer.frame = CGRectOffset(self.bounds, self.bounds.size.width, 0);
    maskLayer.contents = (id)(image.CGImage);
    _gradientLayer.mask = maskLayer;
}

Demo地址

https://github.com/codelyw/iOSDemo

参考

iOS Animations by Tutorials

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容