CALayer 詳解,calayer詳解
CALayer 詳解
- CALayer 詳解
- 綜述
- UIView 和CALayer的區別
- 屬性
- 其他重要屬性
- 重要方法
綜述
UIView的繼承結構為:UIResponder:NSObject。可以看出UIView的直接父類為UIResponder類,.CALayer的繼承結構:NSObject,直接從NSObject繼承,因為缺少了UIResponder類,由上可見UIResponder是用來響應事件的,也就是說UIView可以響應使用者事件,所以CALayer不能響應任何的使用者事件,UIView是在/System/Library/Frameworks/UIKit.framework中定義的。
我們都知道UIKit主要是用來構建使用者介面並且是可以響應事件的。CALayer在/System/Library/Frameworks/QuartzCore.framework定義的。而且CALayer作為一個低級的可以承載繪製內容的底層對象出現在該架構中。
UIView 和CALayer的區別
綜上來看UIView與CALayer的最大區別在於UIView可以響應使用者事件,而CALayer不可以。UIView側重於對顯示內容的管理,CALayer側重於對內容的繪製。QuartzCore是iOS中提供映像繪製的基礎庫,並且CALayer是定義在該架構中的,所以UIView是對CALayer的封裝。UIView和CALayer相互依賴,UIView依賴於CALayer提供的內容,CALayer依賴UIView提供的容器來顯示繪製的內容。但歸根到底CALayer是這一切的基礎,如果沒有CALayer,UIView自身也不會存在,UIView是一個特殊的CALayer的實現,添加了響應事件的能力。
其實UIView之所以能顯示在螢幕上,完全是因為它內部的一個圖層,在建立UIView對象時,UIView內部會自動建立一個圖層(即CALayer對象),通過UIView的layer屬性可以訪問這個層,通過操作這個CALayer對象,可以很方便地調整UIView的一些介面屬性,比如:陰影、圓角大小、邊框寬度和顏色等
蘋果官方文檔:
Core Animation doesn’t provide a means for actually displaying layers in a window, they must be hosted by a view. When paired with a view, the view must provide event-handling for the underlying layers, while the layers provide display of the content.
The view system in iOS is built directly on top of Core Animation layers. Every instance of UIView automatically creates an instance of a CALayer class and sets it as the value of the view’s layer property. You can add sublayers to the view’s layer as needed.
On Mac OS X you must configure an NSView instance in such a way that it can host a layer
屬性
設定背景色,
陰影的偏差值,
陰影的半徑,
陰影的顏色,
陰影的透明度,
子層的frame值。
把新的層add到view的層裡。
設定邊緣寬度
設定邊緣顏色
代碼塊:
CALayer *subLayer=[CALayerlayer];
subLayer.frame=CGRectMake(80,140, 100, 100);subLayer.backgroundColor=[UIColorredColor].CGColor;subLayer.cornerRadius=15;subLayer.shadowColor=[UIColorblueColor].CGColor;subLayer.shadowOffset=CGSizeMake(0,2.0);subLayer.shadowOpacity=1.0;subLayer.borderColor=[UIColoryellowColor].CGColor;subLayer.borderWidth=3.0;[self.view.layeraddSublayer:subLayer];```
其他重要屬性
1、masksToBounds : 很重要的屬性,可以用此屬性來防止子項目大小溢出父元素,如若防止溢出,設為 true
2、shadowColor:設定陰影
3、shadowOpacity; 陰影透明度
4、shadowOffset;陰影位移
5、shadowRadius:陰影圓角
6、contents 設定layer內容,可以為image
7、sublayers 子layers
8、superlayer 父layer
重要方法
1、addSublayer: add new layer
2、removeFromSuperlayer
3、insertSublayer:atIndex:
4、insertSublayer:below:
5、insertSublayer:above:
6、replaceSublayer:with:
以上6方法跟UIView類似,不在贅述