1. 程式人生 > >OC 顏色漸變動畫和動畫組

OC 顏色漸變動畫和動畫組

#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]


#import "ViewController.h"

@interface ViewController (){
    UIView * _v;
    NSNumber * _from;
    NSNumber * _to;
    
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _v = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    _v.backgroundColor = [UIColor redColor];
    [self.view addSubview:_v];
    
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 80, 40)];
    [btn setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    [btn setTitle:@"開始" forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(beginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:btn];
    
    UIButton * btn2 = [[UIButton alloc] initWithFrame:CGRectMake(200, 300, 80, 40)];
    [btn2 setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    [btn2 setTitle:@"結束" forState:(UIControlStateNormal)];
    [btn2 addTarget:self action:@selector(beginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:btn2];

    _from = 0;
    _to = [NSNumber numberWithFloat:M_PI_4];
    
    
}


- (void)beginBtn:(UIButton *)sender{

    [self animations:sender from:_from to:_to];
}

-(void)animations:(UIButton *)sender from:(NSNumber *)from to:(NSNumber *)to{
    
    
    CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    
    CABasicAnimation * ani2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    

    if ([sender.currentTitle isEqualToString:@"開始"]) {
        ani.fromValue = (__bridge id _Nullable)(([UIColor redColor].CGColor));
        ani.toValue = (__bridge id _Nullable)([UIColor greenColor].CGColor);
        ani2.fromValue = from;
        ani2.toValue = to;

    }else{
        ani.fromValue = (__bridge id _Nullable)([UIColor greenColor].CGColor);
        ani.toValue = (__bridge id _Nullable)([UIColor redColor].CGColor);
        ani2.fromValue = to;
        ani2.toValue = from;
        
    }
    CAAnimationGroup * groupAni = [[CAAnimationGroup alloc] init];
    groupAni.animations = @[ani,ani2];
    groupAni.fillMode = kCAFillModeForwards;
    groupAni.removedOnCompletion = false;
    groupAni.duration  = 1;
    [_v.layer addAnimation:groupAni forKey:@"backgroundColor"];
    
}
@end