轉載註明 出處 http://blog.csdn.net/zhaoyabei,謝謝。
使用CAShapeLayer與UIBezierPath可以實現不在view的drawRect方法中就畫出一些想要的圖形。
1.背景知識:
- UIBezierPath:UIBezierPath是在UIKit中的一個類,繼承於NSObject,可以創建基於矢量的路徑.此類是Core Graphics框架關於path的一個OC封裝。使用此類可以定義常見的圓形、多邊形等形狀。我們使用直線、弧(arc)來創建複雜的曲線形狀。每一個直線段或者曲線段的結束的地方是下一個的開始的地方。每一個連接的直線或者曲線段的集合成爲subpath。一個UIBezierPath對象定義一個完整的路徑包括一個或者多個subpaths。
- CAShapeLayer:CAShapeLayer顧名思義,繼承於CALayer。每個CAShapeLayer對象都代表着將要被渲染到屏幕上的一個任意的形狀(shape)。具體的形狀由其path(類型爲CGPathRef)屬性指定。普通的CALayer是矩形,所以需要frame屬性。CAShapeLayer初始化時也需要指定frame值,但它本身沒有形狀,它的形狀來源於其屬性path。CAShapeLayer有不同於CALayer的屬性,它從CALayer繼承而來的屬性在繪製時是不起作用的。
2.開始繪製:
這裏繪製三個圖形,圓形,環形,不規則多邊形。
關鍵代碼如下:
#import "ViewController.h"
@interface ViewController ()
{
//三個CAShapeLayer
CAShapeLayer*circleLayer;
CAShapeLayer*loopLayer;
CAShapeLayer*polygonLayer;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//對三個CAShapeLayer進行初始化
circleLayer=[CAShapeLayer new];
circleLayer.frame=CGRectMake(0, 0, 160, 200);
//fillColor和strokeColor的區別是 一個爲填充色,一個爲描邊色
circleLayer.fillColor=[UIColor blueColor].CGColor;
circleLayer.strokeColor=[UIColor redColor].CGColor;
loopLayer=[CAShapeLayer new];
loopLayer.frame=CGRectMake(160, 0, 160, 200);
loopLayer.fillColor=nil;
loopLayer.lineCap = kCALineCapRound;
loopLayer.strokeColor=[UIColor cyanColor].CGColor;
loopLayer.lineWidth=10;
polygonLayer=[CAShapeLayer new];
polygonLayer.frame=CGRectMake(0, 200, 320, 200);
polygonLayer.fillColor=nil;
polygonLayer.strokeColor=[UIColor greenColor].CGColor
;
//添加到主視圖的layer中
[self.view.layer addSublayer:circleLayer];
[self.view.layer addSublayer:loopLayer];
[self.view.layer addSublayer:polygonLayer];
}
//環形按鈕觸發的事件
- (IBAction)buttonAction:(id)sender {
UIBezierPath*path=[UIBezierPath bezierPathWithArcCenter:CGPointMake(80, 80) radius:80 startAngle:0 endAngle:M_PI*2 clockwise:YES];
// [[UIColor redColor]setStroke];
loopLayer.path=path.CGPath;
}
//圓
- (IBAction)circle:(id)sender {
UIBezierPath*path=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 160, 160) cornerRadius:80];
circleLayer.path=path.CGPath;
}
//多邊形
- (IBAction)polygon:(id)sender {
UIBezierPath*path=[UIBezierPath new];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(0, 50)];
[path addLineToPoint:CGPointMake(50, 50)];
[path addLineToPoint:CGPointMake(150, 50)];
[path addLineToPoint:CGPointMake(200, 100)];
[path closePath];//將起點與結束點相連接
polygonLayer.path=path.CGPath;
}
@end
點擊按鈕後,圖形顯示,效果圖: