Layer: draw/animate the content
View: interactions
CALayer: 2D layer
CATransformLayer: 3D layer(Z depth)
- bounds
- frame
- anchorPoint: default is center(0.5,0.5)
- position: top-left corner is (0,0)
- (CALayer *)addPlaneToLayer:(CALayer*)container size:(CGSize)size position:(CGPoint)point color:(UIColor*)color
{
CALayer *plane = [CALayer layer];
//Define position,size and colors
plane.backgroundColor = [color CGColor];
plane.opacity = 0.6;
plane.frame = CGRectMake(0, 0, 640, 300);
plane.position = point;
plane.anchorPoint = CGPointMake(0.5, 0.5);
plane.borderColor = [[UIColor colorWithWhite:1.0 alpha:0.5]CGColor];
plane.borderWidth = 3;
plane.cornerRadius = 10;
//Add the layer to the container layer
[container addSublayer:planer];
}
CATransform3DTranslate
CATransform3DRotate
// set transform to the plane
CATransform3D t = CATransform3DIdentity;
t = CATransform3DRotate(t, 45.0f * M_PI / 180.0f, 0, 1, 0); // rotation: Y axis(0,1,0)
plane.transform = t;
// set matrix perspective to the plane
#define degToRad(x) (x * M_PI / 180.0f)
CATransform3D t = CATransform3DIdentity;
//Add perspective
t.m34 = 1.0/ -100;
//t.m34 = 1.0/ -500;
t = CATransform3DRotate(t, degToRad(45.0), 0, 1, 0);
plane.transform = t;
Animation
- (void)startAnimation
{
CALayer *container = [CALayer layer];
container.frame = CGRectMake(0, 0, 640, 400);
[self.view.layer addSublayer:container];
CALayer *plane = [self addPlaneToLayer:container size:CGSizeMake(40,80) position:CGPointMake(280, 160) color:[UIColor brownColor]];
// animation sequence
double time = 0;
CABasicAnimation *ani1 = [self createAnimation:@"transform.rotation.x" fromValue:@0 toValue:@(M_PI) beginTime:time duration:1];
time += 1;
CABasicAnimation *ani2 = [self createAnimation:@"position" fromValue:[NSValue valueWithCGPoint:plane.position] toValue:[NSValue valueWithCGPoint:CGPointMake(20, 40)] beginTime:time duration:2];
time += 2;
CABasicAnimation *ani3 = [self createAnimation:@"position" fromValue:[NSValue valueWithCGPoint:CGPointMake(20, 40)] toValue:[NSValue valueWithCGPoint:plane.position] beginTime:time duration:0.5];
time += 0.5;
// added to group
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = @[ani1, ani2, ani3];
group.duration = time;
group.removedOnCompletion = NO;
group.fillMode = kCAFillModeForwards;
group.repeatCount = HUGE;
[plane addAnimation:group forKey:nil];
}
- (CABasicAnimation *)createAnimation:(NSString *)keyPath fromValue:(id)fromValue toValue:(id)toValue beginTime:(double)beginTime duration:(double)duration
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
animation.fromValue = fromValue;
animation.toValue = toValue;
animation.beginTime = beginTime;
animation.duration = duration;
//animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
return animation;
}