今天笔者要说一说layer(层),因为最近一直在学习动画,要想把动画学好,就离不开layer。
首先要知道CAlayer包含在QuartzCore框架里,我们能看到的都是一般都是view,比如button,textView,label等等,layer和view的关系就好比是画布和画板的关系,没有画板,画布不知道要在哪里展示,同样的,没有画布,画板里什么也都没有,因为view没有绘制的功能。
view和layer的关系,(图片来自网络)
我们再来看一下layer的一下属性
/** Geometry and layer hierarchy properties. **/
/* The bounds of the layer. Defaults to CGRectZero. Animatable. */
@property CGRect bounds;
/* The position in the superlayer that the anchor point of the layer's
* bounds rect is aligned to. Defaults to the zero point. Animatable. */
@property CGPoint position;
/* The Z component of the layer's position in its superlayer. Defaults
* to zero. Animatable. */
@property CGFloat zPosition;
/* Defines the anchor point of the layer's bounds rect, as a point in
* normalized layer coordinates - '(0, 0)' is the bottom left corner of
* the bounds rect, '(1, 1)' is the top right corner. Defaults to
* '(0.5, 0.5)', i.e. the center of the bounds rect. Animatable. */
@property CGPoint anchorPoint;
/* The Z component of the layer's anchor point (i.e. reference point for
* position and transform). Defaults to zero. Animatable. */
@property CGFloat anchorPointZ;
/* A transform applied to the layer relative to the anchor point of its
* bounds rect. Defaults to the identity transform. Animatable. */
@property CATransform3D transform;
1. bounds
用来设置其大小的
2 .position
设置其位置
3. zPosition
是这是在Z坐标轴的位置,这里默认是0,手机的坐标系是左手螺旋定则,我们一般看到的view或者layer一般是在水平,X,Y轴坐标上的(平面,Z=0),
4. anchorPoint
这是瞄点,用来决定其上面的哪个点是position属性所指的位置,如果我们不修改position,那么其旋转等操作是都是以position所指的位置,进行变换,估计会有同学不是特别的理解。确实,不怎么好理解,笔者在学习动画的时候,也是花了一些时间才理解的
5. anchorPointz
和上面的第三个属性差不多
6.CATransform3D
这是对其做一些旋转等操作要使用的
7.这里要多说一下,我们在设置layer的时候,
很少使用frame,通常用bounds和position来设置位置和大小;同样的还有透明度用opacity,不用alpha;中心点用position,不用center
下面通过两个简单的例子做进一步的解释
1.demoA
效果图如下:
代码如下:
self.moveCirleLayer = [CALayer layer];
self.moveCirleLayer.bounds = CGRectMake(0, 0, 50, 50);
self.moveCirleLayer.position = self.view.center;
self.moveCirleLayer.cornerRadius = 25;
self.moveCirleLayer.backgroundColor = [UIColor redColor].CGColor;
self.moveCirleLayer.shadowColor = [UIColor blackColor].CGColor;
//x向右为正,y向下为正
self.moveCirleLayer.shadowOffset = CGSizeMake(3, 3);
//一定要设置shadowOpacity ,因为shadowOpacity默认是0,会不显示阴影
self.moveCirleLayer.shadowOpacity = 0.8;
//self.moveCirleLayer.masksToBounds = true;
[self.view.layer addSublayer:self.moveCirleLayer];
1.只要这是cornerRadius 是大小的一般的时候,就会是圆形,
2.这里设置了阴影,shadowoffset是其位置便宜多少,x向右为正,y向下为正,默认是(0,-3),同时为了要显示出来,就必须设置shadowOpacity的值,因为默认是0,不显示的。
3.估计有的同学会设置masksToBounds为YES,这时候就会发现阴影不见了,消失了。原因是这句话的意思是超过其部分就要裁剪,所以阴影当然就显示啦。
demoB,先上效果图:
这里很简单,就是显示一张图片,代码如下:
self.imageLayer = [CALayer layer];
self.imageLayer.bounds = CGRectMake(0, 0, 200, 200);
self.imageLayer.position = self.view.center;
self.imageLayer.backgroundColor = (__bridge CGColorRef _Nullable)([UIColor yellowColor]);
self.imageLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"bb.jpeg"].CGImage);
[self.view.layer addSublayer:self.imageLayer];
是不是很简单呀