CAShapeLayer 簡(jiǎn)介:
<li> CAShapeLayer繼承于CALayer,可以使用CALayer的全部屬性;
<li> CAShapeLayer需要和貝塞爾曲線結(jié)合使用才更有意義。貝塞爾曲線可以為其提供形狀,而單獨(dú)使用CAShapeLayer是沒(méi)有任何意義的;
<li> 使用CAShapeLayer與貝塞爾曲線可以實(shí)現(xiàn)不在View的DrawRect方法中畫(huà)出一些想要的圖形。
貝塞爾曲線(UIBezierPath) 簡(jiǎn)介:
<li> UIBezierPath這個(gè)類在UIKit中,是CoreGraphics框架關(guān)于路徑path的一個(gè)封裝,使用此類可以定義簡(jiǎn)單的形狀。
<li> UIBezierPath對(duì)象是對(duì)CGPathRef數(shù)據(jù)類型的封裝。一般使用UIBezierPath都是在重寫(xiě)View的-drawRect方法中使用 ,
步驟:
1. 重寫(xiě) -drawRect方法;
2. 創(chuàng)建UIBezierPath對(duì)象;
3. 使用方法 -moveToPoint 設(shè)置初始點(diǎn);
4. 根據(jù)具體要求使用UIBezierPath類的實(shí)例方法(畫(huà)線、矩形、圓形 等等)
5. 設(shè)置UIBezierPath對(duì)象的相關(guān)屬性(eg: lineWidth 、lineJoinStyle 、aPath.lineCapStyle 、color 等等);
6. 使用行程或者填充方法結(jié)束繪圖。
關(guān)于CAShapeLayer和DrawRect的比較:
<li>drawRect:drawRect屬于CoreGraphics框架,占用CPU,消耗性能大;
<li>CAShapeLayer:CAShapeLayer屬于CoreAnimation框架,通過(guò)GPU來(lái)渲染圖形,節(jié)省性能,動(dòng)畫(huà)渲染直接提交給手機(jī)GPU,不消耗內(nèi)存。
CAShapeLayer的使用:
<li>繪制特別的形狀
1、CAShapeLayer有一個(gè)神奇的屬性 - Path ,用這個(gè)屬性配合上UIBezierPath這個(gè)類就可以達(dá)到神奇的效果。
/** CAShapeLayer */
// 創(chuàng)建path
UIBezierPath * path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(80, 180)];
[path addCurveToPoint:CGPointMake(300, 180) controlPoint1:CGPointMake(100, 80) controlPoint2:CGPointMake(250, 280)];
// 創(chuàng)建CAShapeLayer
CAShapeLayer * shapelayer = [[CAShapeLayer alloc] init];
// 添加到要要顯示的View的圖層中
[self.view.layer addSublayer:shapelayer];
// 將需要繪制的曲線交給shapelayer對(duì)象
shapelayer.path = path.CGPath;
// 填充顏色
shapelayer.fillColor = [UIColor redColor].CGColor;
// 曲線的顏色
shapelayer.strokeColor = [UIColor orangeColor].CGColor;
// 曲線的寬度
shapelayer.lineWidth = 10;
總結(jié):可以不需要通過(guò)重寫(xiě)-drawRect方法去實(shí)現(xiàn)圖形的繪制,更加的隨機(jī),高性能。
2、一些特殊的圖形也可以通過(guò)CAShapeLayer繪制出來(lái),如:
// 設(shè)置繪制圖形的大小
CGSize finalSize = CGSizeMake(CGRectGetWidth(self.view.frame), 600);
CGFloat layerHeight = finalSize.height * 0.2;
// 創(chuàng)建shapeLayer
CAShapeLayer *bottomCurveLayer = [[CAShapeLayer alloc]init];
// 創(chuàng)建path
UIBezierPath *path = [[UIBezierPath alloc]init];
// 設(shè)置起點(diǎn)
[path moveToPoint:CGPointMake(0, finalSize.height - layerHeight)];
// 左側(cè)的邊線
[path addLineToPoint:CGPointMake(0, finalSize.height - 1)];
// 底部的邊線
[path addLineToPoint:CGPointMake(finalSize.width, finalSize.height - 1)];
// 右側(cè)的邊線
[path addLineToPoint:CGPointMake(finalSize.width, finalSize.height - layerHeight)];
// 頂部的曲線
[path addQuadCurveToPoint:CGPointMake(0, finalSize.height - layerHeight) controlPoint:CGPointMake(finalSize.width / 2, (finalSize.height - layerHeight) - 40)];
// UIBezierPath提高需要繪制的圖形,交給CAShapeLayer對(duì)象渲染圖形
bottomCurveLayer.path = path.CGPath;
bottomCurveLayer.fillColor = [UIColor orangeColor].CGColor;
[self.view.layer addSublayer:bottomCurveLayer];
總結(jié):UIBezierPath提供需要繪制的圖形,而CAShapeLayer提供圖形的渲染顯示到View,不需要在重寫(xiě)-drawRect中拿到圖形上下文。