绘图-几种基本统计图的实现分析

2017-06-20  本文已影响0人  進无尽

前言

在开发中我们会遇到各种统计图,或者各种绘图,本文通过对基本三大统计图:折线图、柱状图、扇形图的实现来掌握基本统计图的绘制,在下一篇文中会带来复杂一些的绘图案例分析,循序渐进达、触类旁通达到绘制各式各样图表的能力。


折线图

折线图.gif

通过自定义UIView使用自定义init方法赋值数据源,后调用 UIView的drawRect方法进行绘制。
重绘的时候 [self setNeedsDisplay]; 会自动调用 drawRect 方法。

绘制折线的时候最基本的是绘制直线、绘制圆点、绘制数据

绘制虚线
 CAShapeLayer设置 虚线宽,线间距   数组第一个是虚线中实现的长度,第二个是虚线中空白的宽度。
  设置一个 UIBezierPath 绘制好路径赋值给  CAShapeLayer即可。
 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:5], nil]];

避免出现上图上的效果图,两种方法:

柱状图

柱状图.gif

自定义 UUBar类,展示的是单个柱状的效果,在 UUBarChart类中调用生成多个柱状的效果。

UUBar中 使用CAShapeLayer 、UIBezierPath、CABasicAnimation可实现动态柱状图

CAShapeLayer设置
_chartLine.fillColor   = [[UIColor whiteColor] CGColor];
_chartLine.lineWidth   = self.frame.size.width;

路线设置    
UIBezierPath *progressline = [UIBezierPath bezierPath];
起点
[progressline moveToPoint:CGPointMake(self.frame.size.width/2.0, self.frame.size.height+30)];
 终点
 [progressline addLineToPoint:CGPointMake(self.frame.size.width/2.0, (1 - grade) * self.frame.size.height+15)];

[progressline setLineWidth:1.0];
[progressline setLineCapStyle:kCGLineCapSquare];
_chartLine.path = progressline.CGPath;

if (_barColor) {
    _chartLine.strokeColor = [_barColor CGColor];
}else{
    _chartLine.strokeColor = [UUGreen CGColor];
}
动画设置
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.5;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
pathAnimation.autoreverses = NO;
[_chartLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"];

扇形图

使用Core Graphics绘制扇形 动态扇形图.gif

小结

考虑到篇幅,这篇文就只介绍折线、柱状、扇形这三大基本统计图的绘制,原理都是一样的,只是需要一些思路和技巧,下篇会带来一些复杂些的绘图案例分析。

上一篇 下一篇

猜你喜欢

热点阅读