目录[-]
- 一重要参数
- 二几何变形Transforming a Layers Geometry
- 三Layer数层结构Layer-Tree Hierarchy
- 四提供Layer内容Providing Layer Content
- 五动画
- 六CALayer的子类们
一.重要参数
bounds,frame,position属于基本的几何定位,相互之间数值变化会相互影响
anchorPoint:单位参数(0-1)表示,变形(transform)时候的变换源点
zPosition:相当于css中z-index的概念,Apple建议不要用这个来替代CALayer层次设置。
cornerRadius:圆角
二.几何变形(Transforming a Layer‘s Geometry)
1.用CATransform3D系列方法
[cpp] view plaincopyprint?
- //将CGAffineTransform转换成CATransform3D
- layer1_1.transform=CATransform3DMakeAffineTransform(CGAffineTransformMakeScale(1, -1));
- //CATransform3D系列方法
- 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
[cpp] view plaincopyprint?
- CATransform3D trans=CATransform3DIdentity;
- NSLog(@"%f",trans.m44);
- //不能是1除以,一定要1.0除以1000(zDistance)
- //wrong trans.m34=1/100.00
- 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)
[cpp] view plaincopyprint?
- [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
[cpp] view plaincopyprint?
- -(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];
- [email protected]"cube";
- anim.subtype=kCATransitionFromRight;
- }
- return anim;
- //不执行任何动画
- //return nil;
- }
苹果文档种提供了修改sublayers默认动画的方法
[cpp] view plaincopyprint?
- NSMutableDictionary *cActions=[NSMutableDictionary dictionaryWithDictionary:[layer1_1 actions]];
- [cActions setObject:[NSNull null] forKey:@"sublayers"];
- layer1_1.actions=cActions;
实现CAAction Protocol
代理类中实现方法runActionForKey:object:arguments
[cpp] view plaincopyprint?
- -(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];
- [email protected]"cube";
- anim.subtype=kCATransitionFromRight;
- }
- [(CALayer*)anObject addAnimation:anim forKey:@"contets"];
- }
触发runActionForKey
[cpp] view plaincopyprint?
- //添加自定义的action以及对应的触发方法所在的代理,应该可以定义一个动画子类(CAAnimation)
- layer1.actions = [NSDictionary dictionaryWithObjectsAndKeys:[[FCLayerDelegate alloc]init], @"test", nil];
- //实际触发的地方,当设置test参数,其实最后触发的是runActionForKey种的立方体旋转
- [layer1 setValue:[NSNumber numberWithInt:19] forKey:@"test"];
四.提供Layer内容(Providing Layer Content)
1.contents属性设置CGImageRef
[cpp] view plaincopyprint?
- layer1.contents=(id)image1.CGImage;
2.用delegate来提供内容
a)displayLayer:(CALayer*)
b)-(void)drawLayer:(CALayer*) inContext:(CGContextRef)
[cpp] view plaincopyprint?
- //声明代理
- @interface FCLayerDeledegate : NSObject
- @end
- //实现代理
- @implementation FCLayerDelegate
- //覆盖这个方法,就不会执行后面的方法,2者取其一,根据传入的值来判断下一步操作
- -(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
[cpp] view plaincopyprint?
- //执行代码
- 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种
[cpp] view plaincopyprint?
- layer1_3.contentsGravity=kCAGravityBottomLeft;
- layer1_3.contents=(id)image3.CGImage;
- //layer1_3.contentsGravity=kCAGravityResizeAspectFill;
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 针对某个属性的设置变化
[cpp] view plaincopyprint?
- 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.transform=CATransform3DTranslate(CATransform3DIdentity, 0, 0, 100);
- [layer1 addAnimation:anim forKey:@"layer1Rotation"];
b)CAKeyframeAnimation
关键帧(key frame)有2种方式提供:
参数path,创建CGPathRef
path:CGPathRef 一般用于移动复杂的位置,如下例:
[cpp] view plaincopyprint?
- 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;
- //设置keyTimes path加了2个点,所以将duration设置成了2段,前面一段快3/10,后面一段慢7/10
- 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"的话,则是图像切换。
[cpp] view plaincopyprint?
- 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”,则是变换坐标
[cpp] view plaincopyprint?
- 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)
[cpp] view plaincopyprint?
- [CATransaction begin];
- [CATransaction setValue:[NSNumber numberWithFloat:.5f] forKey:kCATransactionAnimationDuration];
- layer1.position=CGPointMake(0, 0);
- layer1.opacity=0;
- [CATransaction commit];
通过事务可以修改implicit 动画的时间,否则没有办法修改。
4.动画过渡(Transition)
[cpp] view plaincopyprint?
- //CATransition
- CATransition *animation = [CATransition animation];
- animation.delegate = self;
- animation.duration = 2;
- animation.timingFunction = UIViewAnimationCurveEaseInOut;
- //animation.type = kCATransitionFade;
- animation.type = @"cube";
- animation.subtype = kCATransitionFromLeft;
- //2个view交换
- 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,并且可以根据设置的参数,进行一个渐变
[cpp] view plaincopyprint?
- //每个单元的小layers设置
- 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;//superLayer是否启用3D景深计算
- //设置景深
- CATransform3D transform = CATransform3DIdentity;
- transform.m34 = -1 / 2000.0f;
- xLayer.transform=transform;
甚至可以对layer加入组合式的动画,从而各个元素会有序的一起动画,主要的方法如下:
这个是针对layer的instanceTransform,从而可以影响每一个cell进行同样动画的移动,下面是进行平移的动画
[cpp] view plaincopyprint?
- - (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差不多,主要介绍下参数
[cpp] view plaincopyprint?
- // Configure the particle emitter to the top edge of the screen
- CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
- snowEmitter.emitterPosition = CGPointMake(self.view.bounds.size.width / 2.0, -30);//设置发射位置,这个和emitterMode有关
- snowEmitter.emitterZPosition=50;//发射点z的位置,这个和emitterMode有关
- snowEmitter.emitterSize = CGSizeMake(self.view.bounds.size.width * 2.0, 0.0);//发射点的范围,这个和emitterMode有关
- snowEmitter.emitterDepth=100;
- //从线上发射
- // snowEmitter.emitterMode = kCAEmitterLayerOutline;
- // snowEmitter.emitterShape = kCAEmitterLayerLine;
- //从一个立方体内发射出,这样的话雪花会有不同的大小在3D的情况下
- snowEmitter.emitterMode = kCAEmitterLayerVolume;
- snowEmitter.emitterShape = kCAEmitterLayerCuboid;
- //设置发射单元
- CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
- snowflake.birthRate = 3.0;//每秒发生1个
- snowflake.lifetime = 120.0;//生存时间为120秒
- snowflake.velocity = 20; //初始速度
- snowflake.velocityRange = 10;//初始速度的随机范围
- snowflake.yAcceleration = 10;//y轴加速度,当然还有z,x轴
- //snowflake.emissionRange = -0.5 * M_PI; // 发射角度范围 ,这个参数一设置,似乎方向只能朝屏幕内,就是z的负轴
- 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];
- // Make the flakes seem inset in the background
- snowEmitter.shadowOpacity = 1.0;
- snowEmitter.shadowRadius = 0.0;
- snowEmitter.shadowOffset = CGSizeMake(0.0, 1.0);
- snowEmitter.shadowColor = [[UIColor whiteColor] CGColor];
- //snowflake.emissionLatitude=-M_PI_2;//按照Z轴旋转
- snowEmitter.preservesDepth=YES;
- CATransform3D transform = CATransform3DIdentity;
- transform.m34 = -1.0/300.0f;
- self.view.layer.transform=transform;
- // Add everything to our backing layer below the UIContol defined in the storyboard
- snowEmitter.emitterCells = [NSArray arrayWithObject:snowflake];
- [self.view.layer insertSublayer:snowEmitter atIndex:0];
主要是3DZ轴方向的应用,如果越靠近你的视野,则图片更大,这个效果可以通过设置父Layer的景深来实现。