1.畫直線
- (void)drawRect:(CGRect)rect
{
//獲得處理的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//指定直線樣式
CGContextSetLineCap(context, kCGLineCapSquare);
//直線寬度
CGContextSetLineWidth(context, 2.0);
//設置顏色
CGContextSetRGBStrokeColor(context,0.314, 0.486, 0.859, 1.0);
//開始繪制
CGContextBeginPath(context);
//畫筆移動到點(31,170)
CGContextMoveToPoint(context,31, 70);
//下一點
CGContextAddLineToPoint(context,129, 148);
//下一點
CGContextAddLineToPoint(context,159, 148);
//繪制完成
CGContextStrokePath(context);
}
2.畫折線圖(曲線圖)
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [[UIBezierPath alloc] init];
//初始點
CGPoint startPoint;
//移動到初始點
[path moveToPoint:startPoint];
//是否為曲線圖
BOOL isCurve;
//點的集合
NSArray *pointArray;
//設置點之間的水平距離
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.動態(tài)繪制曲線圖
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIBezierPath *path = [[UIBezierPath alloc] init];
//初始點
CGPoint startPoint;
//移動到初始點
[path moveToPoint:startPoint];
//是否為曲線圖
BOOL isCurve;
//點的集合
NSArray *pointArray;
//設置點之間的水平距離
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];
//添加動畫
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//繪制時間
pathAnimation.duration = plot.pointArray.count * 0.3;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];