动画过程的layer,添加点击效果

2017-08-25  本文已影响0人  淘代码者
//
//  ViewController.m
//  CATrancation
//
//  Created by apple on 17/8/8.
//  Copyright © 2017年 Wang. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIView *changeView;
@property (nonatomic, strong) CALayer *layer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.changeView.hidden = YES;
    CALayer *layer = [CALayer layer];
    layer.position = CGPointMake(self.view.frame.size.width/2, 50);
    layer.bounds = CGRectMake(0, 0, 100, 100);
    layer.backgroundColor = [UIColor lightGrayColor].CGColor;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //get the touch point
    CGPoint point = [[touches anyObject] locationInView:self.view];
    NSLog(@"钱self.layer = %@ self.layer.presentationlayer = %@",NSStringFromCGRect(self.layer.frame),NSStringFromCGRect(self.layer.presentationLayer.frame));
    //check if we've tapped the moving layer
    if ([self.layer.presentationLayer hitTest:point]) {
        //randomize the layer background color
        CGFloat red = arc4random() / (CGFloat)INT_MAX;
        CGFloat green = arc4random() / (CGFloat)INT_MAX;
        CGFloat blue = arc4random() / (CGFloat)INT_MAX;
        self.layer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
    } else {
        //otherwise (slowly) move the layer to new position
        [CATransaction begin];
        [CATransaction setAnimationDuration:4.0];
        [CATransaction setCompletionBlock:^{
            NSLog(@"内self.layer = %@ self.layer.presentationlayer = %@",NSStringFromCGRect(self.layer.frame),NSStringFromCGRect(self.layer.presentationLayer.frame));
        }];
        self.layer.position = point;
        [CATransaction commit];
    }
    NSLog(@"后self.layer = %@ self.layer.presentationlayer = %@",NSStringFromCGRect(self.layer.frame),NSStringFromCGRect(self.layer.presentationLayer.frame));

}

- (IBAction)changeColor:(id)sender {
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    self.layer.actions = @{@"backgroundColor":transition};
    self.layer.backgroundColor = [self randomColor].CGColor;
}

- (UIColor *)randomColor{
    CGFloat R = arc4random_uniform(256.f)/255.f;
    CGFloat G = arc4random_uniform(256.f)/255.f;
    CGFloat B = arc4random_uniform(256.f)/255.f;
    return [UIColor colorWithRed:R green:G blue:B alpha:1.f];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
上一篇下一篇

猜你喜欢

热点阅读