關(guān)于圖形繪制
今天在項(xiàng)目中有一個小需求,需要在視圖上繪制一個圓,內(nèi)部有一個點(diǎn),點(diǎn)不能超出圓外,于是找了一些關(guān)于圖形繪制方面的資料。以下只記錄一些自己用到的知識點(diǎn)。
1.view的drawRect方法。該方法不能手動調(diào)用,是由系統(tǒng)自動調(diào)用的,在需要調(diào)用該方法時候,可以通過調(diào)用setNeedsDisplay方法,這時候系統(tǒng)會去調(diào)用drawRect方法。一般情況下,創(chuàng)建一個繼承自UIView的類,在該類中重寫drawRect方法。例如:
一個繼承自UIView的類MyView,在其MyView.m文件中重寫:
方法一:
-(void)drawRect:(CGRect)rect {
// 獲取處理的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 設(shè)置線條樣式
CGContextSetLineCap(context, kCGLineCapRound);
// 設(shè)置線條粗細(xì)寬度
CGContextSetLineWidth(context, 1.0);
// 設(shè)置顏色
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1);
// 開始一個起始路徑
CGContextBeginPath(context);
// 畫圓
CGContextAddArc(context, 120, 120, 60, 0, M_PI * 2, YES);
// 連接上面定義的坐標(biāo)點(diǎn)
CGContextStrokePath(context);
}
方法二:
-(void)drawRect:(CGRect)rect {
// 創(chuàng)建UIBezierPath對象
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
// 畫圓
[bezierPath addArcWithCenter:CGPointMake(120, 120) radius:60 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
// 設(shè)置線寬
bezierPath.lineWidth = 1;
// 設(shè)置stroke顏色
[[UIColor blackColor] setStroke];
// 繪制
[bezierPath stroke];
}
在控制器中添加該視圖就能看到視圖中的繪制的圓形 .
2.使用CAShapeLayer與UIBezierPath 繪圖
使用CAShapeLayer與UIBezierPath 繪圖可以實(shí)現(xiàn)不在view的drawRect方法中就畫出一些想要的圖形;
步驟:
1.新建UIBezierPath 對象bezierPath;
2.新建CAShapeLayer對象caShapeLayer;
3.將bezierPath的CGPath賦值給caShapeLayer的path,即caShapeLayer.path = bezierPath.CGPath;
4.把caShapeLayer添加到某個顯示該圖形的layer中。
例如,在viewController中作了如下操作
- (void)setUpUI {
CGPoint arcCenter = CGPointMake([UIScreen mainScreen].bounds.size.width/2, 120);
CGFloat radius = 80;
CGFloat startAngle = 0.0;
CGFloat endAngle = M_PI * 2;
// 創(chuàng)建 UIBezierPath對象
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:arcCenter radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
// 創(chuàng)建CAShapeLayer對象
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
layer.path = bezierPath.CGPath;
layer.fillColor = [UIColor clearColor].CGColor;
layer.strokeColor = [UIColor blackColor].CGColor;
layer.lineWidth = 5;
// 將CAShapeLayer對象添加到視圖的layer中
[self.view.layer addSublayer:layer];
}
運(yùn)行程序后,會看到視圖中繪制的圓。