如何畫一個三角形

屏幕快照 2016-11-23 下午5.36.29.png

畫三角形和其他圖形同理,這里主要介紹下畫三角形。

1??.使用圖形上下文:CGContextRef
2??.使用UIBeizerPath:
3??.使用UIBeizerPath&CAShapeLayer

注意方法1??,2??需要在view的drawRect方法里重繪。

方法一:CGContextRef(需要新建一個自定義view,在view的drawRect方法里進行繪制操作)
- (void)drawRect:(CGRect)rect
{
    // 設置背景色
    [[UIColor whiteColor] set];
    
    //拿到當前視圖準備好的畫板
    CGContextRef  context = UIGraphicsGetCurrentContext();
    
    //利用path進行繪制三角形
    CGContextBeginPath(context);//標記
    
    CGContextMoveToPoint(context,
                         _pointOne.x, _pointOne.y);//設置起點
    
    CGContextAddLineToPoint(context,
                            _pointTwo.x ,  _pointTwo.y);
    
    CGContextAddLineToPoint(context,
                            _pointThr.x, _pointThr.y);
    
    CGContextClosePath(context);//路徑結束標志,不寫默認封閉
    
    [_fillColor setFill];  //設置填充色
    
    [_fillColor setStroke]; //設置邊框顏色
    
    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)];
    
    // 最后的閉合線是可以通過調用closePath方法來自動生成的,也可以調用-addLineToPoint:方法來添加
    //  [path addLineToPoint:CGPointMake(20, 20)];
    
    [path closePath];
    
    // 設置線寬
    path.lineWidth = 1.5;
    
    // 設置填充顏色
    UIColor *fillColor = [UIColor greenColor];
    [fillColor set];
    [path fill];
    
    // 設置畫筆顏色
    UIColor *strokeColor = [UIColor blueColor];
    [strokeColor set];
    
    // 根據我們設置的各個點連線
    [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。后續會把UIBezierPath的相關學習內容整理發出來。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容