使用兩種方法繪制直線。
繪圖的一般步驟:
- 獲取上下文
- 創(chuàng)建路徑并設(shè)置路徑
- 將屬性添加到上下文
- 設(shè)置上下文屬性
- 繪制路徑
- 釋放路徑
繪制直線的代碼:
#pragma mark 繪制直線
- (void)drawLine
{
//提示 使用ref的對象不用使用*
//1.獲取上下文.-UIView對應(yīng)的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//2.創(chuàng)建可變路徑并設(shè)置路徑
//當我們開發(fā)動畫的時候,通常制定對象運動的路線,然后由動畫負責(zé)動畫效果
CGMutablePathRef path = CGPathCreateMutable();
//2-1.設(shè)置起始點
CGPathMoveToPoint(path, NULL, 50, 50);
//2-2.設(shè)置目標點
CGPathAddLineToPoint(path, NULL, 200, 200);
CGPathAddLineToPoint(path, NULL, 50, 200);
//封閉路徑
//第一種方法
//CGPathAddLineToPoint(path, NULL, 50, 50);
//第二張方法
CGPathCloseSubpath(path);
//3.將路徑添加到上下文
CGContextAddPath(context, path);
//4.設(shè)置上下文屬性
//4.1.設(shè)置線條顏色
/*
red 0~1.0 red / 255
green 0~1.0 green / 255
blue 0~1.0 blue / 255
plpha 透明度 0 ~ 1.0
0 完全透明
1.0 完全不透明
提示:在使用rgb設(shè)置顏色時。最好不要同時指定rgb和alpha,否則會對性能造成影響。
線條和填充默認都是黑色
*/
CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);
//設(shè)置填充顏色
CGContextSetRGBFillColor(context, 0, 1.0, 0, 1.0);
//4.2 設(shè)置線條寬度
CGContextSetLineWidth(context, 3.0f);
//設(shè)置線條頂點樣式
CGContextSetLineCap(context, kCGLineCapRound);
//設(shè)置連接點的樣式
CGContextSetLineJoin(context, kCGLineJoinRound);
//設(shè)置線條的虛線樣式
/*
虛線的參數(shù):
phase:相位,虛線的起始位置=通常使用 0 即可,從頭開始畫虛線
lengths:長度的數(shù)組
count : lengths 數(shù)組的個數(shù)
*/
CGFloat lengths[2] = {20.0,10.0};
CGContextSetLineDash(context, 0, lengths, 3);
//5.繪制路徑
/*
kCGPathStroke:劃線(空心)
kCGPathFill: 填充(實心)
kCGPathFillStroke:即劃線又填充
*/
CGContextDrawPath(context, kCGPathFillStroke);
//6.釋放路徑
CGPathRelease(path);
}
第二種方法:
使用默認context進行繪圖
#pragma mark 使用默認context進行繪圖
- (void)drawLine2
{
//1.獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//2.設(shè)置當前上下問路徑
//設(shè)置起始點
CGContextMoveToPoint(context, 50, 50);
//增加點
CGContextAddLineToPoint(context, 200, 200);
CGContextAddLineToPoint(context, 50, 200);
//關(guān)閉路徑
CGContextClosePath(context);
//3.設(shè)置屬性
/*
UIKit會默認導(dǎo)入 core Graphics框架,UIKit對常用的很多的唱歌方法做了封裝
UIColor setStroke設(shè)置邊線顏色
uicolor setFill 設(shè)置填充顏色
*/
[[UIColor redColor]setStroke];
[[UIColor blueColor]setFill];
// [[UIColor yellowColor]set];
//4.繪制路徑
CGContextDrawPath(context, kCGPathFillStroke);
}
在frawRect()中進行繪圖(必須drawRect中):
- (void)drawRect:(CGRect)rect {
//獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
[self drawLine];
}