畫三角形和其他圖形同理缀皱,這里主要介紹下畫三角形。
1??.使用圖形上下文:CGContextRef
2??.使用UIBeizerPath:
3??.使用UIBeizerPath&CAShapeLayer
注意方法1??上岗,2??需要在view的drawRect方法里重繪凄鼻。
方法一:CGContextRef(需要新建一個(gè)自定義view随橘,在view的drawRect方法里進(jìn)行繪制操作)
- (void)drawRect:(CGRect)rect
{
// 設(shè)置背景色
[[UIColor whiteColor] set];
//拿到當(dāng)前視圖準(zhǔn)備好的畫板
CGContextRef context = UIGraphicsGetCurrentContext();
//利用path進(jìn)行繪制三角形
CGContextBeginPath(context);//標(biāo)記
CGContextMoveToPoint(context,
_pointOne.x, _pointOne.y);//設(shè)置起點(diǎn)
CGContextAddLineToPoint(context,
_pointTwo.x , _pointTwo.y);
CGContextAddLineToPoint(context,
_pointThr.x, _pointThr.y);
CGContextClosePath(context);//路徑結(jié)束標(biāo)志喂分,不寫默認(rèn)封閉
[_fillColor setFill]; //設(shè)置填充色
[_fillColor setStroke]; //設(shè)置邊框顏色
CGContextDrawPath(context,
kCGPathFillStroke);//繪制路徑path
}
方法二:UIBeizerPath (同一,需要建自定義view)
// 畫三角形
- (void)drawTrianglePath {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(20, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width - 40, 20)];
[path addLineToPoint:CGPointMake(self.frame.size.width / 2, self.frame.size.height - 20)];
// 最后的閉合線是可以通過調(diào)用closePath方法來自動(dòng)生成的太防,也可以調(diào)用-addLineToPoint:方法來添加
// [path addLineToPoint:CGPointMake(20, 20)];
[path closePath];
// 設(shè)置線寬
path.lineWidth = 1.5;
// 設(shè)置填充顏色
UIColor *fillColor = [UIColor greenColor];
[fillColor set];
[path fill];
// 設(shè)置畫筆顏色
UIColor *strokeColor = [UIColor blueColor];
[strokeColor set];
// 根據(jù)我們?cè)O(shè)置的各個(gè)點(diǎn)連線
[path stroke];
}
方法三:UIBeizerPath&CAShapeLayer(路徑使用UIBizerPath繪制妻顶,用CAShapeLayer生成最終圖形)
// CAShapeLayer and UIBezierPath
- (void)setupViewByCAShapeLayer {
CAShapeLayer *triangleLayer = [[CAShapeLayer alloc]init];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(200, 300)];
[path addLineToPoint:CGPointMake(250, 200)];
[path addLineToPoint:CGPointMake(300, 300)];
triangleLayer.path = path.CGPath;
[self.view.layer addSublayer:triangleLayer];
[triangleLayer setFillColor:[UIColor cyanColor].CGColor];
}
三種方法看需求使用。第三種使用較多蜒车,可通過UIBezierPath的靈活性繪制很多樣式的View讳嘱。后續(xù)會(huì)把UIBezierPath的相關(guān)學(xué)習(xí)內(nèi)容整理發(fā)出來。