注意其中的圆角生成
CALayer(这里简单地称其为层)。
首先要说的是CALayers 是屏幕上的一个具有可见内容的矩形区域,每个UIView都有一个根CALayer,其所有的绘制(视觉效果)都是在这个layer上进行的。
UILabel*
lable.text
[self.view addSubview:
lable.backgroundColor
[lable release];
// 设定CALayer
self.view.layer.backgroundColor
self.view.layer.cornerRadius
self.view.layer.frame
请注意,我创建的UILable始终随着UIView的根CALayer的缩放而改变位置。)
其次,CALayer的可以影响其外观的特性有:
层的大小尺寸背景色内容(比如图像或是使用
Core Graphics绘制的内容)是否使用圆角是否使用阴影等等
需要说明的是CALayer的大部分属性都可以用来实现动画效果。另外,你可以直接使用CALayer,也可以使用其子类,如CAGradientLayer,CATextLayer, CAShapeLayer等等。
示例
首先在Xcode中创建一个View-based App,CALayer是属于QuartzCore framework的,所以需要引入QuartzCore framework,另外在程序中包括QuartzCore.h。
第一个例子是创建一个带圆角的层,在你的ViewController中的ViewDidLoad中加入下面代码:
// Import QuartzCore.h at the top of the file
#import <QuartzCore/QuartzCore.h>
// Uncomment viewDidLoad and add the following lines
self.view.layer.backgroundColor
self.view.layer.cornerRadius
self.view.layer.frame
然后添加一个带阴影效果的子层,加入下列代码:
CALayer
sublayer.backgroundColor
sublayer.shadowOffset
sublayer.shadowRadius
sublayer.shadowColor
sublayer.shadowOpacity
sublayer.frame
[self.view.layer addSublayer:sublayer];
为子层增加内容(图片),你还可以设置层的边框,代码如下:
sublayer.contents
sublayer.borderColor
sublayer.borderWidth
如 果你希望子层也是圆角怎么办?你可能说很容易设置cornerRadius属性就行。实际上你即算是设置了cornerRadius属性,图片仍然不会显 示圆角。你还需要设置masksToBounds为YES。但是这样做还是不够的,因为如果是这样,这个层的阴影显示就没有了。简单的实现方法如下(通过 两个层来实现):
CALayer
sublayer.backgroundColor
sublayer.shadowOffset
sublayer.shadowRadius
sublayer.shadowColor
sublayer.shadowOpacity
sublayer.frame
sublayer.borderColor
sublayer.borderWidth
sublayer.cornerRadius
[self.view.layer addSublayer:sublayer];
CALayer
imageLayer.frame
imageLayer.cornerRadius
imageLayer.contents
imageLayer.masksToBounds
[sublayer addSublayer:imageLayer];
最 后,还介绍一下自绘图型的实现,其要点是要设置所绘制层的delegate。比如在我们的例子中使用ViewController作为delegate, 那么就需要在ViewController中实现drawLayer:inContext方法,对层进行绘制工作。另外,还需要调用 setNeedsDisplay,来通知层需要进行绘制了,于是层才会通过对delegate的drawLayer:inContext方法进行调用。
代码如下:
void
}
-(void)drawLayer:(CALayer
还需要注意,radians是一个自定义函数:
static