繪圖的步驟:
- 1.獲取上下文
- 2.創(chuàng)建路徑(描述路徑)
- 3.把路徑添加到上下文
- 4.渲染上下文
通常在這個方法里面繪制圖形(drawRect)
為什么要再drawRect里面繪圖? 只有在這個方法里面才能獲取到跟View的layer相關(guān)聯(lián)的圖形上下文
什么時候調(diào)用? 當(dāng)這個View要顯示的時候才會調(diào)用drawRect繪制圖形
注意:rect是當(dāng)前控件的bounds
- (void)drawRect:(CGRect)rect {
// Drawing code
// 如何繪制曲線
// 原生繪制方法
// 獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 描述路徑
// 設(shè)置起點
CGContextMoveToPoint(ctx, 50, 50);
// cpx:控制點的x
CGContextAddQuadCurveToPoint(ctx, 150, 20, 250, 50);
// 渲染上下文
CGContextStrokePath(ctx);
}
- (void)drawUIBezierPathState
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50, 50)];
[path addLineToPoint:CGPointMake(200, 200)];
path.lineWidth = 10;
[[UIColor redColor] set];
[path stroke];
UIBezierPath *path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointMake(0, 0)];
[path1 addLineToPoint:CGPointMake(30, 60)];
[[UIColor greenColor] set];
path1.lineWidth = 3;
[path1 stroke];
}
- (void)drawCtxState
{
// 獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 描述路徑
//起點
CGContextMoveToPoint(ctx, 50, 50);
CGContextAddLineToPoint(ctx, 100, 50);
// 設(shè)置起點
CGContextMoveToPoint(ctx, 80, 60);
// 默認下一根線的起點就是上一根線終點
CGContextAddLineToPoint(ctx, 100, 200);
// 設(shè)置繪圖狀態(tài),一定要在渲染之前
// 顏色
[[UIColor redColor] setStroke];
// 線寬
CGContextSetLineWidth(ctx, 5);
// 設(shè)置連接樣式
CGContextSetLineJoin(ctx, kCGLineJoinBevel);
// 設(shè)置頂角樣式
CGContextSetLineCap(ctx, kCGLineCapRound);
// 渲染上下文
CGContextStrokePath(ctx);
}
pragma mark - 繪圖的幾種方式
pragma mark - 繪圖第三種方式
- (void)drawLine2
{
// UIKit已經(jīng)封裝了一些繪圖的功能
// 貝瑟爾路徑
// 創(chuàng)建路徑
UIBezierPath *path = [UIBezierPath bezierPath];
// 設(shè)置起點
[path moveToPoint:CGPointMake(50, 50)];
// 添加一根線到某個點
[path addLineToPoint:CGPointMake(200, 200)];
// 繪制路徑
[path stroke];
// NSLog(@"%@",NSStringFromCGRect(rect));
}
pragma mark - 繪圖第二種方式
- (void)drawLine1
{
// 獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 描述路徑
// 設(shè)置起點
CGContextMoveToPoint(ctx, 50, 50);
CGContextAddLineToPoint(ctx, 200, 200);
// 渲染上下文
CGContextStrokePath(ctx);
}
pragma mark - 最原始的繪圖方式
- (void)drawLine
{
// 1.獲取圖形上下文
// 目前我們所用的上下文都是以UIGraphics
// CGContextRef Ref:引用 CG:目前使用到的類型和函數(shù) 一般都是CG開頭 CoreGraphics
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.描述路徑
// 創(chuàng)建路徑
CGMutablePathRef path = CGPathCreateMutable();
// 設(shè)置起點
// path:給哪個路徑設(shè)置起點
CGPathMoveToPoint(path, NULL, 50, 50);
// 添加一根線到某個點
CGPathAddLineToPoint(path, NULL, 200, 200);
// 3.把路徑添加到上下文
CGContextAddPath(ctx, path);
// 4.渲染上下文
CGContextStrokePath(ctx);
}