之前开发的时候了解过一些,现在决定从头整理,并将学习CALayer中发现的一些之前没注意的小细节记录下来:
1 positon 属性
该属性设置的不是layer的中心点,而是锚点的位置anchorPoint:锚点范围为:(0,1),默认跟layer的中心点重合,为(0.5,0.5)。
因为frame属性并不具备动画效果,所以在开发的过程中,主要使用bounds和position的结合。
2 图形绘制的时候 上下颠倒的问题
如果只是绘制一张图片,直接设置contents属性:

该方法是不需要考虑坐标问题的。
但是如果复杂的情况下使用
-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx
方法的话,就需要考虑图形绘制的上下颠倒问题,解决的方法有两种:
1)

2)绕x轴旋转180°:

3)相对于直接的代码表示,还可以通过keyPath设置旋转,如:

这样写最主要的是搞明白keyPath有哪些:

想要讨论的是第二种方法,绕轴旋转到底是如何绕的?该如何理解?
首先,原图如下:

如果是绕y轴的话,你想象坐标原点在中心点的下方,图形的最下方是x轴,y轴经过中心点,这样的话就很容易理解绕轴旋转的原理了:

同理,如果是绕x轴旋转的话,就是y轴在最左边,x轴经过中心点。
最后,我再解释一下旋转角度:
M_PI:3.141593
M_PI_2:1.570796
所以在转换度数的时候应该是:例 45°:45 /180*M_PI
3 使用自定义图层绘图
自定义图形指的就是继承于CALayer的子类,通过调用类中的-(void)drawInContext:(CGContextRef)ctx方法来绘图。为了显示再定义一个UIView的子类,UIView在创建的时候会自动的指定自身为CALayer的代理,所以在UIView中需要调用setNeedsDisplay方法。UIView会自动创建位图上下文,通过视图中的-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx方法将CGContextRef传递给CALayer方法中。而在UIView的draw:inContext:方法中会调用其drawRect:方法,在drawRect:方法中使用UIGraphicsGetCurrentContext()方法得到的上下文正是前面创建的上下文。


网友评论