CALayer04——隐式动画
一、基本介绍
每一个UIView内部都默认关联着一个CALayer,我们可用称这个Layer为Root Layer(根层)
所有的非Root Layer,也就是手动创建的CALayer对象,都存在着隐式动画
什么是隐式动画?
当对非Root Layer的部分属性进行修改时,默认会自动产生一些动画效果
而这些属性称为Animatable Properties(可动画属性)
列举几个常见的Animatable Properties:
bounds:用于设置CALayer的宽度和高度。修改这个属性会产生缩放动画
backgroundColor:用于设置CALayer的背景色。修改这个属性会产生背景色的渐变动画
position:用于设置CALayer的位置。修改这个属性会产生平移动画
可以通过动画事务(CATransaction)关闭默认的隐式动画效果
[CATransaction begin];
[CATransaction setDisableActions:YES];
//[CATransaction setAnimationDuration:5];
self.myview.layer.position = CGPointMake(10, 10);
[CATransaction commit];
二、时钟案例
2.1 需要完成的效果图
2.2 代码
//
// ViewController.m
// 03_UIView67_时钟
//
// Created by 杞文明 on 17/6/11.
// Copyright © 2017年 杞文明. All rights reserved.
//
#import "ViewController.h"
//每一秒旋转的度数
#define perSecA 6
//每一分旋转的度数
#define perMinA 6
//每一小时旋转的度数
#define perHourA 30
//每一分,时针旋转的度数
#define perMinHour 0.5
#define angle2Rad(angle) ((angle) / 180.0 * M_PI)
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *clockView;
/** 当前的秒针 */
@property (nonatomic, weak) CALayer *secL;
/** 当前的分针 */
@property (nonatomic, weak) CALayer *minL;
/** 当前的针针 */
@property (nonatomic, weak) CALayer *hourL;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initHourPointer];
[self initMinPointer];
[self initSecPointer];
//创建定时器
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
[self timeChange];
}
//初始化时针
-(void)initHourPointer{
_hourL = [self createPointer:CGSizeMake(4, 50) withColor:[UIColor blueColor]];
}
//初始化分针
-(void)initMinPointer{
_minL = [self createPointer:CGSizeMake(3, 70) withColor:[UIColor blackColor]];
}
//初始化秒针
-(void)initSecPointer{
_secL = [self createPointer:CGSizeMake(1, 80) withColor:[UIColor redColor]];
}
//创建指针
-(CALayer*)createPointer:(CGSize)size withColor: (UIColor*) backColor{
CALayer * pointer = [CALayer layer];
pointer.bounds = CGRectMake(0, 0, size.width, size.height);
pointer.backgroundColor = backColor.CGColor;
pointer.anchorPoint = CGPointMake(0.5, 0.9);
pointer.position = CGPointMake(_clockView.bounds.size.width*0.5, _clockView.bounds.size.height*0.5);
[_clockView.layer addSublayer:pointer];
return pointer;
}
//时间改变
-(void)timeChange{
//获取时间
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *cmp = [cal components:(NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond) fromDate:[NSDate date]];
NSInteger curSec = cmp.second;
NSInteger curMin = cmp.minute;
NSInteger curHour = cmp.hour;
NSLog(@" %ld : %ld : %ld",curHour,curMin,curSec);
//计算秒针的位置
CGFloat secA = curSec * perSecA;
_secL.transform = CATransform3DMakeRotation(angle2Rad(secA), 0, 0, 1);
//计算分钟位置
CGFloat minA = curMin * perMinA;
_minL.transform = CATransform3DMakeRotation(angle2Rad(minA), 0, 0, 1);
//计算时钟位置
CGFloat hourA = curHour * perHourA + curMin * perMinHour;
_hourL.transform = CATransform3DMakeRotation(angle2Rad(hourA), 0, 0, 1);
}
@end