maskView

maskView是UIView的一个属性,对应的CALayer也有一个mask,他们两个的作用是一样的,同样的一个东西。这个属性类似一个遮罩,设置maskView后,原本的view只能看到maskView不透明的部分。这个属性用来做动画可以实现一些很好玩的东西。

很简单,主要是利用设置maskView后,原本的view只能看到maskView不透明的部分。


 
maskView.gif
#import "HZSGradientProgressView.h"

@interface HZSGradientProgressView ()

@property (nonatomic, strong) UIView *mask;

@end

@implementation HZSGradientProgressView

+ (Class)layerClass {
    return [CAGradientLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)init {
    return [self initWithFrame:CGRectZero];
}

- (void)commonInit {
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    NSArray *colors = [NSArray arrayWithObjects:(__bridge id)[UIColor redColor].CGColor,
                                                    (__bridge id)[UIColor orangeColor].CGColor,
                                                    (__bridge id)[UIColor yellowColor].CGColor,
                                                    (__bridge id)[UIColor greenColor].CGColor,
                                                    (__bridge id)[UIColor blueColor].CGColor,
                                                    (__bridge id)[UIColor purpleColor].CGColor,
                                                    nil];
    gradientLayer.startPoint = CGPointMake(0.0, 0.5);
    gradientLayer.endPoint = CGPointMake(1.0, 0.5);
    gradientLayer.colors = colors;
    
    _mask = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, self.bounds.size.height)];
    _mask.backgroundColor = [UIColor blackColor];
    self.maskView = _mask;
    
    _value = 0.0;
}

- (void)setValue:(CGFloat)value {
    if (value == _value) return;
    
    value = MAX(value, 0);
    value = MIN(value, 1);
    _value = value;
    _mask.frame = CGRectMake(0, 0, self.bounds.size.width * _value, self.bounds.size.height);
    [self colorsAnimation];
}

- (void)colorsAnimation {
    CAGradientLayer *gradientLayer = (CAGradientLayer *)self.layer;
    NSArray *colors = gradientLayer.colors;
    if (colors == nil) return;
    
    NSMutableArray *temp = [colors mutableCopy];
    id last = colors.lastObject;
    [temp removeLastObject];
    [temp insertObject:last atIndex:0];
    
    gradientLayer.colors = temp;
}

 

posted @ 2018-03-06 09:14  Holyday  阅读(185)  评论(0编辑  收藏  举报