iOS 绘制曲线图

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.动态绘制曲线图

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"];

你可能感兴趣的:(iOS 绘制曲线图)