1.畫(huà)直線
- (void)drawRect:(CGRect)rect
{
//獲得處理的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//指定直線樣式
CGContextSetLineCap(context, kCGLineCapSquare);
//直線寬度
CGContextSetLineWidth(context, 2.0);
//設(shè)置顏色
CGContextSetRGBStrokeColor(context,0.314, 0.486, 0.859, 1.0);
//開(kāi)始繪制
CGContextBeginPath(context);
//畫(huà)筆移動(dòng)到點(diǎn)(31,170)
CGContextMoveToPoint(context,31, 70);
//下一點(diǎn)
CGContextAddLineToPoint(context,129, 148);
//下一點(diǎn)
CGContextAddLineToPoint(context,159, 148);
//繪制完成
CGContextStrokePath(context);
}
2.畫(huà)折線圖(曲線圖)
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [[UIBezierPath alloc] init];
//初始點(diǎn)
CGPoint startPoint;
//移動(dòng)到初始點(diǎn)
[path moveToPoint:startPoint];
//是否為曲線圖
BOOL isCurve;
//點(diǎn)的集合
NSArray *pointArray;
//設(shè)置點(diǎn)之間的水平距離
CGFloat xInstance = 10;
for (int i = 0; i < pointArray.count; i++) {
CGPoint endPoint =CGPointMake(xInstance *i, [pointArray[i] floatValue]);
CGFloat centerX = (startPoint.x + endPoint.x)/2;
CGPoint crl1 = CGPointMake(centerX, startPoint.y);
CGPoint crl2 = CGPointMake(centerX, endPoint.y);
if (isCurve) {
//添加曲線路徑嗡贺,用于曲線圖
[path addCurveToPoint:endPoint controlPoint1:crl1 controlPoint2:crl2];
startPoint = endPoint;
}
else
{
//添加直線路徑她混,用于折線圖
[path addLineToPoint:endPoint];
}
}
//線的顏色
[[UIColor yellowColor] set];
//線寬
CGContextSetLineWidth(ctx, 2);
// 將路徑添加到圖形上下文
CGContextAddPath(ctx, path.CGPath);
// 渲染
CGContextStrokePath(cox);
3.動(dòng)態(tài)繪制曲線圖
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [[UIBezierPath alloc] init];
//初始點(diǎn)
CGPoint startPoint;
//移動(dòng)到初始點(diǎn)
[path moveToPoint:startPoint];
//是否為曲線圖
BOOL isCurve;
//點(diǎn)的集合
NSArray *pointArray;
//設(shè)置點(diǎn)之間的水平距離
CGFloat xInstance = 10;
for (int i = 0; i < pointArray.count; i++) {
CGPoint endPoint =CGPointMake(xInstance *i, [pointArray[i] floatValue]);
CGFloat centerX = (startPoint.x + endPoint.x)/2;
CGPoint crl1 = CGPointMake(centerX, startPoint.y);
CGPoint crl2 = CGPointMake(centerX, endPoint.y);
if (isCurve) {
//添加曲線路徑叁执,用于曲線圖
[path addCurveToPoint:endPoint controlPoint1:crl1 controlPoint2:crl2];
startPoint = endPoint;
}
else
{
//添加直線路徑,用于折線圖
[path addLineToPoint:endPoint];
}
}
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.bounds;
pathLayer.path = path.CGPath;
//線的顏色
pathLayer.strokeColor = [plot.lineColor CGColor];
//線的填充色
pathLayer.fillColor = nil;
//線寬
pathLayer.lineWidth = 2;
pathLayer.lineJoin = kCALineJoinBevel;
[self.layer addSublayer:pathLayer];
//添加動(dòng)畫(huà)
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//繪制時(shí)間
pathAnimation.duration = plot.pointArray.count * 0.3;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];