渐变颜色进度条

直接上效果图:

渐变颜色进度条_第1张图片
effect.gif

直接上代码:

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@property (nonatomic, strong) NSMutableArray *colorsArray;

@property (nonatomic, assign) CGFloat process;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = CGRectMake(50, 200, 1, 2);
    self.gradientLayer.startPoint = CGPointMake(0, 0.5);
    self.gradientLayer.endPoint = CGPointMake(1, 0.5);
    
    self.colorsArray = [NSMutableArray array];
    for (NSInteger i = 0; i <= 360; i += 5) {
        UIColor *color = [UIColor colorWithHue:1.0 * i / 360
                                    saturation:1.0
                                    brightness:1.0
                                         alpha:1.0];
        [self.colorsArray addObject:(id)[color CGColor]];
    }
    
    self.gradientLayer.colors = self.colorsArray;
    [self.view.layer addSublayer:self.gradientLayer];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.05 repeats:YES block:^(NSTimer * _Nonnull timer) {
        
        self.process += 0.01;
        self.process = self.process > 1 ? 1 : self.process;
        self.gradientLayer.frame = CGRectMake(50, 200, self.process * (SCREEN_WIDTH - 100), 2);
        
        UIColor *lastColor = [self.colorsArray lastObject];
        [self.colorsArray removeLastObject];
        [self.colorsArray insertObject:lastColor atIndex:0];
        self.gradientLayer.colors = self.colorsArray;
    }];
}

@end

内容比较简单,只是一个思路,共同学习。

你可能感兴趣的:(渐变颜色进度条)