先来看看效果,正反变化都有:
这里博主用了组动画的方式,通过两种转换来完成:
1.通过bounds和position
2.通过transform.scale.y和position
通过bounds和position
1.创建一个layer
CALayer *itemLayer = [CALayer layer];
itemLayer.frame = CGRectMake(50, 100, 50, 200);
itemLayer.backgroundColor = [UIColor redColor].CGColor;
[baseView.layer addSublayer:itemLayer];
2.写bounds的动画
CGRect frame = itemLayer.frame;
CABasicAnimation *aniBounds = [CABasicAnimation animationWithKeyPath:@"bounds"];
aniBounds.fromValue = [NSValue valueWithCGRect:CGRectMake(50, 100, 50, 0)];
aniBounds.toValue = [NSValue valueWithCGRect:CGRectMake(50, 100, CGRectGetWidth(frame), CGRectGetHeight(frame))];
3.写position的动画(position在UIView中类似center)
CABasicAnimation *aniPosition = [CABasicAnimation animationWithKeyPath:@"position"];
aniPosition.fromValue = [NSValue valueWithCGPoint:CGPointMake(50 + (CGRectGetMaxX(frame)-50)/2, 100)];
aniPosition.toValue = [NSValue valueWithCGPoint:CGPointMake(50 + (CGRectGetMaxX(frame)-50)/2,100 + (CGRectGetMaxY(frame)-100)/2)];
//需要反方向延伸的
aniPosition.fromValue = [NSValue valueWithCGPoint:CGPointMake(220 + (CGRectGetMaxX(frame)-220)/2,CGRectGetMaxY(frame))];
aniPosition.toValue = [NSValue valueWithCGPoint:CGPointMake(220 + (CGRectGetMaxX(frame)-220)/2, 100 + (CGRectGetMaxY(frame) - 100)/2)];
CGRectGetMaxX
CGRectGetMaxX //解释一下,它的意思是获取到 x坐标+width 的值,Y对应 y坐标+height 的值 max代表最大,min代表最小最小时x,y坐标不变,宽度为原来的宽度,高度为0;
4.将两个动画组合起来
CAAnimationGroup *anis = [CAAnimationGroup animation];
anis.animations = @[aniBounds,aniPosition];
anis.duration = 1;
anis.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
anis.removedOnCompletion = NO;
anis.fillMode=kCAFillModeForwards;
[itemLayer addAnimation:anis forKey:nil];
你也可以尝试不组合,不组合矩形的position是固定的,两端同时延伸,不是我们要的效果,所以用positon来固定位置。
通过transform.scale.y和position
这里和上面的写法是一样的,区别是没有用bounds,改用了transform.scale.y(高的缩放值)
CABasicAnimation *aniBounds = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
aniBounds.duration = 1;
aniBounds.fromValue = @0.0;
aniBounds.toValue = @1.0;
aniBounds.repeatCount = 1;
[itemLayer addAnimation:aniBounds forKey:@""];
其他的东西是一样的,也许还有其他的写法,博主暂时想不到了,Demo下载地址:点击下载
如果有其他好的方法欢迎和博主沟通!