一.重要参数
bounds,frame,position属于基本的几何定位,相互之间数值变化会相互影响
anchorPoint:单位参数(0-1)表示,变形(transform)时候的变换源点
zPosition:相当于css中z-index的概念,Apple建议不要用这个来替代CALayer层次设置。
cornerRadius:圆角
二.几何变形(Transforming a Layer‘s Geometry)
1.用CATransform3D系列方法
- layer1_1.transform=CATransform3DMakeAffineTransform(CGAffineTransformMakeScale(1, -1));
- layer1_1.transform=CATransform3DMakeScale(-1, 1, 1);
- layer1_1.transform=CATransform3DScale(CATransform3DMakeScale(-2, 1, 1), -1, 1, 1);
- layer1_1.transform=CATransform3DIdentity;
2.修改CATransform3D的data structure
- CATransform3D trans=CATransform3DIdentity;
- NSLog(@"%f",trans.m44);
- trans.m34=-1.0/1000;
- trans = CATransform3DTranslate(trans, 0, 0, -240);
- trans = CATransform3DRotate(trans, d2r(90), 1, 0, 0);
- trans = CATransform3DTranslate(trans, 0, 0, 240);
- [layer1 setTransform:trans];
3.key-valre设置key Paths(rotation,scale,translation)
- [layer1 setValue:[NSNumber numberWithInt:200] forKeyPath:@"transform.translation.x"];
三.Layer数层结构(Layer-Tree Hierarchy)
1.add,insert,remove,replace来进行树状结构的构建
2.重置(Reposition and Resizing)layer
a)你可以通过修改第一点提到的几个参数来调整大小。
b)needsDisplayOnBoundsChange设置YES,则在bounds变化时,自动调用setNeedsDisplay,调用layer的display的方法,或者直接显示调用setNeedsDisplay(不能使用setNeedsDisplayInRect),也会调用自定义layer的display方法。或者是setNeesLayout,调用layer的layoutSubLayers。(PS:无法使用layoutManager和autoResizingMask方法,这个是Mac OS上的方法。)
c)在UIView的layoutSubviews里实现自定义layout的方法。
3.masksToBounds设置YES,则裁剪subLayers。否则不裁剪,subLayers可以超过superLayer的bounds。
4.Action
当更改layer的参数或者将layer添加,删除,隐藏,替换时触发
触发方法可以是子类化CALayer,-(id<CAAction>)actionForKey:(NSString*)key;代理方式-(id<CAAction>)actionForLayer:(CALayer*) forKey:(NSString*)key
- -(id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event{
- CATransition *anim=nil;
- if([event isEqualToString:@"contents"]){
- anim=[CATransition animation];
- anim.duration=2;
- anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
- anim.type=@"cube";
- anim.subtype=kCATransitionFromRight;
- }
- return anim;
-
-
- }
苹果文档种提供了修改sublayers默认动画的方法
- NSMutableDictionary *cActions=[NSMutableDictionary dictionaryWithDictionary:[layer1_1 actions]];
- [cActions setObject:[NSNull null] forKey:@"sublayers"];
- layer1_1.actions=cActions;
实现CAAction Protocol
代理类中实现方法runActionForKey:object:arguments
- -(void)runActionForKey:(NSString *)event object:(id)anObject arguments:(NSDictionary *)dict{
- NSLog(@"runActionForKey:\"%@\" object:%@ arguments:%@", event, anObject, dict);
- CATransition *anim=nil;
- if([event isEqualToString:@"test"]){
- anim=[CATransition animation];
- anim.duration=2;
- anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
- anim.type=@"cube";
- anim.subtype=kCATransitionFromRight;
- }
-
- [(CALayer*)anObject addAnimation:anim forKey:@"contets"];
- }
触发runActionForKey
- layer1.actions = [NSDictionary dictionaryWithObjectsAndKeys:[[FCLayerDelegate alloc]init], @"test", nil];
- [layer1 setValue:[NSNumber numberWithInt:19] forKey:@"test"];
四.提供Layer内容(Providing Layer Content)
1.contents属性设置CGImageRef
- layer1.contents=(id)image1.CGImage;
2.用delegate来提供内容
a)displayLayer:(CALayer*)
b)-(void)drawLayer:(CALayer*) inContext:(CGContextRef)
- @interface FCLayerDeledegate : NSObject
- @end
- @implementation FCLayerDelegate
- -(void)displayLayer:(CALayer *)layer{
- NSLog(@"%@",[layer valueForKey:@"test"]);
- }
- -(void)drawLayer:(CALayer *)ly inContext:(CGContextRef)context
- {
- CGContextSetFillColorWithColor(context, [[UIColor redColor]CGColor]);
- CGContextFillRect(context, ly.bounds);
- }
- @end
- CALayer* layer1_3=[CALayer layer];
- layer1_3.delegate=[[FCLayerDelegate alloc]init];
- [layer1_3 setValue:@"testString" forKey:@"test"];
- [layer1_3 setNeedsDisplay];
ps:以上方法用于CALayer本身(非自己子类)
3) 用子类提供内容
a)display
b)drawInContext:(CGContextRef)
和前面代理模式差不多,只不过少传layer参数,因为layer就是其本身(self);
4)内容的布局
默认情况下,内容图片是会铺开充满整个layer的bounds的,如果要使得contents按照原来尺寸显示在layer中,就要设置ContentsGravity
大致2种参数
1.位置参数,注意,ios坐标是y是相反的,所以bottom就是top
2.设置铺满方式,3种
- layer1_3.contentsGravity=kCAGravityBottomLeft;
- layer1_3.contents=(id)image3.CGImage;
PS:此外contentsCenter这个属性在铺满方式的参数下可以指定拉伸区域,文档中指出是指定拉伸的范围,但是似乎没有作用。暂时忽略。
五.动画
1.动画类簇
a)CAMediaTiming protocol的主要参数
speed:执行速度,如果速度为2,则一个10秒的duration,则只需要5秒完成。子类参数相对父类参数的,如果子类是2,父类是2,则需要2.5秒完成
repeatCount|repeatDuration:重复的次数和重复的间隔 ,如果repeatCount设置成 1e100f则无限重复
fillMode:决定动画结束时候的状态。要和removeOnCompletion参数一起设置才有效。动画结束后的状态并没有影响layer的位置,其实layer还在原来的地方没变。
此外还有duration,autoreverses,beginTime,timeOffset
b)CAAnimation
timingFunction:指定一个CAMediaTimingFunction,有2种提供方式,一种是常量如kCAMediaTimingFunctionLinear,另外一种是自定义2个control points来定制一个时间曲线
functionWithControlPoints::::。
delegate:2个代理方法animationDidStart:和animationDidStop:finished:
2.一般动画
任何CALayer的animated的属性或者CTM改变时候都是动画形式来过渡的,这个称为implicit Animation。这里不多做介绍
主要介绍下(Explicit Animation)显示动画
a)CABasicAnimation 针对某个属性的设置变化
- CABasicAnimation *anim;
- anim=[CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
- anim.duration=8;
- anim.autoreverses=NO;
- anim.repeatCount=2;
- anim.fromValue=[NSNumber numberWithFloat:d2r(0)];
- anim.toValue=[NSNumber numberWithFloat:d2r(-90)];
- [layer1 addAnimation:anim forKey:@"layer1Rotation"];
b)CAKeyframeAnimation
关键帧(key frame)有2种方式提供:
参数path,创建CGPathRef
path:CGPathRef 一般用于移动复杂的位置,如下例:
- CGMutablePathRef path=CGPathCreateMutable();
- CGPathMoveToPoint(path, NULL, 40, 420);
- CGPathAddCurveToPoint(path, NULL, 40, 40, 160, 40, 160, 420);
- CGPathAddCurveToPoint(path, NULL, 160, 40, 280, 40, 280, 420);
- CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"position"];
- anim.path=path;
- anim.duration=3;
-
- anim.rotationMode=kCAAnimationRotateAuto;
- anim.removedOnCompletion = NO;
- anim.fillMode=kCAFillModeForwards;
- anim.calculationMode=kCAAnimationLinear;
- anim.keyTimes=[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:0.3],[NSNumber numberWithFloat:1.0], nil];
- [layer1 addAnimation:anim forKey:@"nm1"];
- CGPathRelease(path);
参数values:array of objects
如果objects是CGImage,key-path是"contents"的话,则是图像切换。
- CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"contents"];
- anim.duration=3;
- anim.values=[NSArray arrayWithObjects:(id)image1.CGImage,(id)image2.CGImage,(id)image3.CGImage,nil];
- [layer1 addAnimation:anim forKey:@"nm2"];
如果objects是CATransform3D的,key-path是“transform”,则是变换坐标
- CAKeyframeAnimation *anim2=[CAKeyframeAnimation animationWithKeyPath:@"transform"];
- anim2.duration=3;
- anim2.repeatCount=1000;
- anim2.autoreverses=YES;
- CATransform3D trans=CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1);
- CATransform3D trans2=CATransform3DScale(CATransform3DIdentity, 1, 1, 1);
- anim2.values=[NSArray arrayWithObjects:[NSValue valueWithCATransform3D:trans],[NSValue valueWithCATransform3D:trans2],nil];
- [layer1 addAnimation:anim2 forKey:@"nm3"];
如果2个同时设置,还可以同时看到动画效果。比方说上述2个就可以看到图片切换并且放大和缩小的效果。
不要针对frame和size等参数设置keyframe动画,似乎没有效果。position是可以的。
3.动画事务(Transaction)
- [CATransaction begin];
- [CATransaction setValue:[NSNumber numberWithFloat:.5f] forKey:kCATransactionAnimationDuration];
- layer1.position=CGPointMake(0, 0);
- layer1.opacity=0;
- [CATransaction commit];
通过事务可以修改implicit 动画的时间,否则没有办法修改。
4.动画过渡(Transition)
- CATransition *animation = [CATransition animation];
- animation.delegate = self;
- animation.duration = 2;
- animation.timingFunction = UIViewAnimationCurveEaseInOut;
- animation.type = @"cube";
- animation.subtype = kCATransitionFromLeft;
- NSUInteger green = [[self.view subviews] indexOfObject:self.greenView];
- NSUInteger blue = [[self.view subviews] indexOfObject:self.blueView];
- [self.view exchangeSubviewAtIndex:green withSubviewAtIndex:blue];
- [layer1 addAnimation:animation forKey:@"animation"];
过渡有view的过渡和layer的过渡,2者是有区别的,网上有个例子transition包含了一共12种变换,相当有用。此外还可以设置startProgress和endProgress,这样就可以让动画执行到某个特定位置,比如说pageCurUp的话,就可以翻到一半,相当的酷哦!
六.CALayer的子类们
随着iOS 5.0的更新,CALayer添加了新的成员,我稍微研究了一些,现在做下总结,有的是新的,有的则是5.0以前的。
1.CAReplicatorLayer
顾名思义,这个类是用来创建重复的layer,并且可以根据设置的参数,进行一个渐变
- CALayer *layer1 = [CALayer layer];
- layer1.position = CGPointMake(10,200);
- layer1.bounds = CGRectMake(0, 0, 20, 20);
- layer1.backgroundColor = [[UIColor yellowColor] CGColor];
- layer1.cornerRadius = 2;
- layer1.shadowColor = [[UIColor blackColor] CGColor];
- layer1.shadowRadius = 4.0f;
- layer1.shadowOffset = CGSizeMake(0.0f, 3.0f);
- layer1.shadowOpacity = .8;
- layer1.opacity = 0.8;
- layer1.borderColor = [[UIColor whiteColor] CGColor];
- layer1.borderWidth = 2.0;
- CAReplicatorLayer *xLayer = [CAReplicatorLayer layer];
- xLayer.instanceCount = 11;
- xLayer.instanceDelay = .2;
- xLayer.instanceGreenOffset = -.03;
- xLayer.instanceRedOffset = -.02;
- xLayer.instanceBlueOffset = -.01;
- xLayer.instanceAlphaOffset = -.05;
- xLayer.instanceTransform =CATransform3DMakeTranslation(25, 0, 200);
- [xLayer addSublayer:layer1];
-
-
- xLayer.preservesDepth = YES;
- CATransform3D transform = CATransform3DIdentity;
- transform.m34 = -1 / 2000.0f;
- xLayer.transform=transform;
甚至可以对layer加入组合式的动画,从而各个元素会有序的一起动画,主要的方法如下:
这个是针对layer的instanceTransform,从而可以影响每一个cell进行同样动画的移动,下面是进行平移的动画
- - (CABasicAnimation *)pushAnimation {
- CABasicAnimation *pushAnim =
- [CABasicAnimation animationWithKeyPath:@"instanceTransform"];
- pushAnim.fromValue =[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(SUBLAYER_WIDTH+INTERSPACE, 0, 0)];
- pushAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(SUBLAYER_WIDTH+INTERSPACE+60, 0, 0)];
- pushAnim.duration = 3.0;
- pushAnim.autoreverses = YES;
- pushAnim.repeatCount = HUGE_VAL;
- pushAnim.timingFunction =
- [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
- return pushAnim;
- }
2.CAEmitterLayer&CAEmitterCell
网上有很多粒子相关的代码,比如雪花的飘动,燃烧的火焰,烟雾效果,其实都是通过这个类的设置来实现的,用法和CAReplicatorLayer差不多,主要介绍下参数
-
- CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
- snowEmitter.emitterPosition = CGPointMake(self.view.bounds.size.width / 2.0, -30);
- snowEmitter.emitterZPosition=50;
- snowEmitter.emitterSize = CGSizeMake(self.view.bounds.size.width * 2.0, 0.0);
- snowEmitter.emitterDepth=100;
-
-
-
-
- snowEmitter.emitterMode = kCAEmitterLayerVolume;
- snowEmitter.emitterShape = kCAEmitterLayerCuboid;
-
- CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
- snowflake.birthRate = 3.0;
- snowflake.lifetime = 120.0;
- snowflake.velocity = 20;
- snowflake.velocityRange = 10;
- snowflake.yAcceleration = 10;
-
-
- snowflake.spin=0.0;
- snowflake.spinRange =- 0.25 * M_PI;
-
- snowflake.contents = (id) [[UIImage imageNamed:@"flake"] CGImage];
- snowflake.color = [[UIColor colorWithRed:0.600 green:0.658 blue:0.743 alpha:1.000] CGColor];
-
- snowEmitter.shadowOpacity = 1.0;
- snowEmitter.shadowRadius = 0.0;
- snowEmitter.shadowOffset = CGSizeMake(0.0, 1.0);
- snowEmitter.shadowColor = [[UIColor whiteColor] CGColor];
-
-
- snowEmitter.preservesDepth=YES;
- CATransform3D transform = CATransform3DIdentity;
- transform.m34 = -1.0/300.0f;
- self.view.layer.transform=transform;
-
- snowEmitter.emitterCells = [NSArray arrayWithObject:snowflake];
- [self.view.layer insertSublayer:snowEmitter atIndex:0];
主要是3DZ轴方向的应用,如果越靠近你的视野,则图片更大,这个效果可以通过设置父Layer的景深来实现。