畫圖入口
關(guān)于畫圖的方法必須寫在這個方法中
frame被確定后,就會執(zhí)行drawRect方法
執(zhí)行
[self setNeedsDisplay];
方法時會重新調(diào)用drawRect方法
- (void)drawRect:(CGRect)rect {
// Drawing code
}
圖形定制
扇形圖
- (void)drawPieChart {
NSMutableArray *array =[NSMutableArray array];
for (int i = 0; i < arc4random_uniform(6) + 1; i++) {
[array addObject:@(RANDOMNUM)];
}
//用來存儲所有值的總和
CGFloat totalF = 0.0;
//計算總和
for (NSNumber *num in array) {
totalF += num.floatValue;
}
//中心點坐標
CGPoint centerP = CGPointMake(130, 140);
//半徑
CGFloat radiusF = 99.0;
//起點坐標
CGFloat startF = 0.0;
//終點坐標
CGFloat endF = 0.0;
for (int i = 0; i < array.count; i++) {
CGFloat currF = [array[i] floatValue];
//所占比例--度數(shù)大小
CGFloat angleF = currF / (totalF*1.0) * M_PI * 2;
startF = endF;
endF = angleF + startF;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radiusF startAngle:startF endAngle:endF clockwise:YES];//clockwise :是否順時針
//增加一條線段到中心點
[path addLineToPoint:centerP];
//關(guān)閉路徑,組成扇形
[path closePath];
//顏色
[RANDOMCOLOR set];
[path fill];
}
}
虛線
- (void)drawDash {
//1.創(chuàng)建上下文
CGContextRef ref = UIGraphicsGetCurrentContext();
//2.創(chuàng)建路徑
UIBezierPath *path = [UIBezierPath bezierPath];
//3.增加起點
[path moveToPoint:CGPointZero];
//4.增加一條線段到某個點
[path addLineToPoint:CGPointMake(99, 99)];
//5.顏色
[[UIColor redColor] set];
//6.線寬
CGContextSetLineWidth(ref, 4);
//6+.虛線
/**
* lengths[] = {4, 2}
* 原理: 實線-4 空白-2 實線-4 空白-2
* lengths[] = {4, 2, 3}
* 原理: 實線-4 空白-2 實線-3 空白-4 實線-2 空白-3
* 先實線后空白,實線和空白的長度為數(shù)組的循環(huán)引用
*/
CGFloat lengths[] = {4, 2};//因為CGContextSetLineDash方法用到的數(shù)組為C語言中的數(shù)組,所以此處數(shù)組用此種格式
CGContextSetLineDash(ref, 0, lengths, 2);//2為lengths的長度
//7.將路徑添加到上下文
CGContextAddPath(ref, path.CGPath);
//8.渲染
// CGContextFillPath(ref);//fill
// CGContextStrokePath(ref);//stroke
CGContextDrawPath(ref, kCGPathFillStroke);//stroke + fill
}
橢圓(圓)
- (void)drawOval {
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(88, 60, 99, 99)];
/**
* set = setFill + setStroke
*/
//邊框
[[UIColor redColor] setStroke];
//填充
[[UIColor yellowColor] setFill];
//線寬
path.lineWidth = 5;
//繪制
[path fill];//fill表示填充
[path stroke];//stroke表示繪制邊框
}
三角形
- (void)drawTriangle {
//創(chuàng)建貝塞爾曲線類(路徑)
UIBezierPath *path = [UIBezierPath bezierPath];
//起點坐標
[path moveToPoint:CGPointMake(20, 80)];
//增加一條線段到某個點
[path addLineToPoint:CGPointMake(220, 280)];
[path addLineToPoint:CGPointMake(230, 30)];
//將路徑閉合,形成三角形
[path closePath];
//設(shè)置線段的顏色
[[UIColor redColor] set];
//設(shè)置線寬
path.lineWidth = 4;
//繪制
[path stroke];
}