前一阵子读到一篇介绍CALayer(这里简单地称其为层)的教程,比较简单易懂,适合初学者,我在这里就不完全翻译了,只是把要点说明一下。
首先要说的是CALayers 是屏幕上的一个具有可见内容的矩形区域,每个UIView都有一个根CALayer,其所有的绘制(视觉效果)都是在这个layer上进行的。(译者注:为验证这点,我写下了如下代码:
1 | UILabel* lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)]; |
请注意,我创建的UILable始终随着UIView的根CALayer的缩放而改变位置。)
其次,CALayer的可以影响其外观的特性有:
- 层的大小尺寸
- 背景色
- 内容(比如图像或是使用Core Graphics绘制的内容)
- 是否使用圆角
- 是否使用阴影
- 等等
需要说明的是CALayer的大部分属性都可以用来实现动画效果。
另外,你可以直接使用CALayer,也可以使用其子类,如CAGradientLayer,CATextLayer, CAShapeLayer等等。
示例
首先在Xcode中创建一个View-based App,CALayer是属于QuartzCore framework的,所以需要引入QuartzCore framework,另外在程序中包括QuartzCore.h。
第一个例子是创建一个带圆角的层,在你的ViewController中的ViewDidLoad中加入下面代码:
1 | // Import QuartzCore.h at the top of the file |
结果如下:
然后添加一个带阴影效果的子层,加入下列代码:
1 | CALayer *sublayer = [CALayer layer]; |
效果图:
为子层增加内容(图片),你还可以设置层的边框,代码如下:
1 | sublayer.contents =(id)[UIImage imageNamed:@"BattleMapSplashScreen.png"].CGImage; |
效果图:
如果你希望子层也是圆角怎么办?你可能说很容易设置cornerRadius属性就行。实际上你即算是设置了cornerRadius属性,图片仍然不会显示圆角。你还需要设置masksToBounds为YES。但是这样做还是不够的,因为如果是这样,这个层的阴影显示就没有了。简单的实现方法如下(通过两个层来实现):
1 | CALayer *sublayer =[CALayer layer]; |
效果图:
最后,还介绍一下自绘图型的实现,其要点是要设置所绘制层的delegate。比如在我们的例子中使用ViewController作为delegate,那么就需要在ViewController中实现drawLayer:inContext方法,对层进行绘制工作。另外,还需要调用setNeedsDisplay,来通知层需要进行绘制了,于是层才会通过对delegate的drawLayer:inContext方法进行调用。
代码如下:
1 | void MyDrawColoredPattern (void*info, CGContextRef context){ |
还需要注意,radians是一个自定义函数:
1 | static inline double radians (double degrees) { return degrees * M_PI/180; } |