单军华
2017-03-03 764722d0366346dc435aa906abdd25655e3b0769
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//
//  PNRadarChart.m
//  PNChartDemo
//
//  Created by Lei on 15/7/1.
//  Copyright (c) 2015年 kevinzhow. All rights reserved.
//
 
#import "PNRadarChart.h"
 
@interface PNRadarChart()
 
@property (nonatomic) CGFloat centerX;
@property (nonatomic) CGFloat centerY;
@property (nonatomic) NSMutableArray *pointsToWebArrayArray;
@property (nonatomic) NSMutableArray *pointsToPlotArray;
@property (nonatomic) UILabel *detailLabel;
@property (nonatomic) CGFloat lengthUnit;
@property (nonatomic) CAShapeLayer *chartPlot;
 
@end
 
 
@implementation PNRadarChart
 
- (id)initWithFrame:(CGRect)frame items:(NSArray *)items valueDivider:(CGFloat)unitValue {
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
 
        //Public iVar
        if ([items count]< 3)//At least three corners of A polygon ,If the count of items is less than 3 will add 3 default values
        {
            NSLog( @"At least three items!");
            NSArray *defaultArray = @[[PNRadarChartDataItem dataItemWithValue:0 description:@"Default"],
                                      [PNRadarChartDataItem dataItemWithValue:0 description:@"Default"],
                                      [PNRadarChartDataItem dataItemWithValue:0 description:@"Default"],
                                      ];
           defaultArray = [defaultArray arrayByAddingObjectsFromArray:items];
            _chartData = [NSArray arrayWithArray:defaultArray];
        }else{
            _chartData = [NSArray arrayWithArray:items];
        }
        _valueDivider = unitValue;
        _maxValue = 1;
        _webColor = [UIColor grayColor];
        _plotColor = [UIColor colorWithRed:.4 green:.8 blue:.4 alpha:.7];
        _fontColor = [UIColor blackColor];
        _graduationColor = [UIColor orangeColor];
        _fontSize = 15;
        _labelStyle = PNRadarChartLabelStyleHorizontal;
        _isLabelTouchable = YES;
        _isShowGraduation = NO;
        
        //Private iVar
        _centerX = frame.size.width/2;
        _centerY = frame.size.height/2;
        _pointsToWebArrayArray = [NSMutableArray array];
        _pointsToPlotArray = [NSMutableArray array];
        _lengthUnit = 0;
        _chartPlot = [CAShapeLayer layer];
        _chartPlot.lineCap = kCALineCapButt;
        _chartPlot.lineWidth = 1.0;
        [self.layer addSublayer:_chartPlot];
        
        [super setupDefaultValues];
         //init detailLabel
        _detailLabel = [[UILabel alloc] init];
        _detailLabel.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.1 alpha:.9];
        _detailLabel.textAlignment = NSTextAlignmentCenter;
        _detailLabel.textColor = [UIColor colorWithWhite:1 alpha:1];
        _detailLabel.font = [UIFont systemFontOfSize:15];
        [_detailLabel setHidden:YES];
        [self addSubview:_detailLabel];
        
        [self strokeChart];
    }
    return self;
}
 
#pragma mark - main
- (void)calculateChartPoints {
    [_pointsToPlotArray removeAllObjects];
    [_pointsToWebArrayArray removeAllObjects];
    
    //init Descriptions , Values and Angles.
    NSMutableArray *descriptions = [NSMutableArray array];
    NSMutableArray *values = [NSMutableArray array];
    NSMutableArray *angles = [NSMutableArray array];
    for (int i=0;i<_chartData.count;i++) {
        PNRadarChartDataItem *item = (PNRadarChartDataItem *)[_chartData objectAtIndex:i];
        [descriptions addObject:item.textDescription];
        [values addObject:[NSNumber numberWithFloat:item.value]];
        CGFloat angleValue = (float)i/(float)[_chartData count]*2*M_PI;
        [angles addObject:[NSNumber numberWithFloat:angleValue]];
    }
    
    //calculate all the lengths
    _maxValue = [self getMaxValueFromArray:values];
    CGFloat margin = 0;
    if (_labelStyle==PNRadarChartLabelStyleCircle) {
        margin = MIN(_centerX , _centerY)*3/10;
    }else if (_labelStyle==PNRadarChartLabelStyleHorizontal) {
        margin = [self getMaxWidthLabelFromArray:descriptions withFontSize:_fontSize];
    }
    CGFloat maxLength = ceil(MIN(_centerX, _centerY) - margin);
    int plotCircles = (_maxValue/_valueDivider);
    if (plotCircles > MAXCIRCLE) {
        NSLog(@"Circle number is higher than max");
        plotCircles = MAXCIRCLE;
        _valueDivider = _maxValue/plotCircles;
    }
    _lengthUnit = maxLength/plotCircles;
    NSArray *lengthArray = [self getLengthArrayWithCircleNum:(int)plotCircles];
 
    //get all the points and plot
    for (NSNumber *lengthNumber in lengthArray) {
        CGFloat length = [lengthNumber floatValue];
        [_pointsToWebArrayArray addObject:[self getWebPointWithLength:length angleArray:angles]];
    }
    int section = 0;
    for (id value in values) {
        CGFloat valueFloat = [value floatValue];
        if (valueFloat>_maxValue) {
            NSString *reason = [NSString stringWithFormat:@"Value number is higher than max -value: %f - maxValue: %f",valueFloat,_maxValue];
            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];
            return;
        }
        
        CGFloat length = valueFloat/_maxValue*maxLength;
        CGFloat angle = [[angles objectAtIndex:section] floatValue];
        CGFloat x = _centerX +length*cos(angle);
        CGFloat y = _centerY +length*sin(angle);
        NSValue* point = [NSValue valueWithCGPoint:CGPointMake(x, y)];
        [_pointsToPlotArray addObject:point];
        section++;
    }
    //set the labels
    [self drawLabelWithMaxLength:maxLength labelArray:descriptions angleArray:angles];
    
 }
#pragma mark - Draw
 
- (void)drawRect:(CGRect)rect {
    // Drawing backgound
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    int section = 0;
    //circles
    for(NSArray *pointArray in _pointsToWebArrayArray){
        //plot backgound
        CGContextRef graphContext = UIGraphicsGetCurrentContext();
        CGContextBeginPath(graphContext);
        CGPoint beginPoint = [[pointArray objectAtIndex:0] CGPointValue];
        CGContextMoveToPoint(graphContext, beginPoint.x, beginPoint.y);
        for(NSValue* pointValue in pointArray){
            CGPoint point = [pointValue CGPointValue];
            CGContextAddLineToPoint(graphContext, point.x, point.y);
        }
        CGContextAddLineToPoint(graphContext, beginPoint.x, beginPoint.y);
        CGContextSetStrokeColorWithColor(graphContext, _webColor.CGColor);
        CGContextStrokePath(graphContext);
        
    }
    //cuts
    NSArray *largestPointArray = [_pointsToWebArrayArray lastObject];
    for (NSValue *pointValue in largestPointArray){
        section++;
        if (section==1&&_isShowGraduation)continue;
        
        CGContextRef graphContext = UIGraphicsGetCurrentContext();
        CGContextBeginPath(graphContext);
        CGContextMoveToPoint(graphContext, _centerX, _centerY);
        CGPoint point = [pointValue CGPointValue];
        CGContextAddLineToPoint(graphContext, point.x, point.y);
        CGContextSetStrokeColorWithColor(graphContext, _webColor.CGColor);
        CGContextStrokePath(graphContext);
    }
    
    
}
 
- (void)strokeChart {
    
    [self calculateChartPoints];
    [self setNeedsDisplay];
    [_detailLabel setHidden:YES];
    
    //Draw plot
    [_chartPlot removeAllAnimations];
    UIBezierPath *plotline = [UIBezierPath bezierPath];
    CGPoint beginPoint = [[_pointsToPlotArray objectAtIndex:0] CGPointValue];
    [plotline moveToPoint:CGPointMake(beginPoint.x, beginPoint.y)];
    for(NSValue *pointValue in _pointsToPlotArray){
        CGPoint point = [pointValue CGPointValue];
        [plotline addLineToPoint:CGPointMake(point.x ,point.y)];
        
    }
    [plotline setLineWidth:1];
    [plotline setLineCapStyle:kCGLineCapButt];
    
    _chartPlot.path = plotline.CGPath;
    
    _chartPlot.fillColor = _plotColor.CGColor;
 
    [self addAnimationIfNeeded];
    [self showGraduation];
}
 
#pragma mark - Helper
 
- (void)drawLabelWithMaxLength:(CGFloat)maxLength labelArray:(NSArray *)labelArray angleArray:(NSArray *)angleArray {
    //set labels
    int labelTag = 121;
    while (true) {
        UIView *label = [self viewWithTag:labelTag];
        if(!label)break;
        [label removeFromSuperview];
    }
    int section = 0;
    CGFloat labelLength = maxLength + maxLength/10;
    
    for (NSString *labelString in labelArray) {
        CGFloat angle = [[angleArray objectAtIndex:section] floatValue];
        CGFloat x = _centerX + labelLength *cos(angle);
        CGFloat y = _centerY + labelLength *sin(angle);
        
        UILabel *label = [[UILabel alloc] init] ;
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:_fontSize];
        label.text = labelString;
        label.tag = labelTag;
        CGSize detailSize = [labelString sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_fontSize]}];
        
        switch (_labelStyle) {
            case PNRadarChartLabelStyleCircle:
                label.frame = CGRectMake(x-5*_fontSize/2, y-_fontSize/2, 5*_fontSize, _fontSize);
                label.transform = CGAffineTransformMakeRotation(((float)section/[labelArray count])*(2*M_PI)+M_PI_2);
                label.textAlignment = NSTextAlignmentCenter;
                
                break;
            case PNRadarChartLabelStyleHorizontal:
                if (x<_centerX) {
                    label.frame = CGRectMake(x-detailSize.width, y-detailSize.height/2, detailSize.width, detailSize.height);
                    label.textAlignment = NSTextAlignmentRight;
                }else{
                    label.frame = CGRectMake(x, y-detailSize.height/2, detailSize.width , detailSize.height);
                    label.textAlignment = NSTextAlignmentLeft;
                }
                break;
            case PNRadarChartLabelStyleHidden:
                [label setHidden:YES];
                break;
            default:
                break;
        }
        [label sizeToFit];
        
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapLabelGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLabel:)];
        [label addGestureRecognizer:tapLabelGesture];
        [self addSubview:label];
        
        section ++;
    }
    
}
 
- (void)tapLabel:(UITapGestureRecognizer *)recognizer {
    UILabel *label=(UILabel*)recognizer.view;
    _detailLabel.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y-30, 50, 25);
    for (PNRadarChartDataItem *item in _chartData) {
        if ([label.text isEqualToString:item.textDescription]) {
            _detailLabel.text =  [NSString stringWithFormat:@"%.2f", item.value];
            break;
        }
    }
    [_detailLabel setHidden:NO];
    
}
 
- (void)showGraduation {
    int labelTag = 112;
    while (true) {
        UIView *label = [self viewWithTag:labelTag];
        if(!label)break;
        [label removeFromSuperview];
    }
    int section = 0;
    for (NSArray *pointsArray in _pointsToWebArrayArray) {
        section++;
        CGPoint labelPoint = [[pointsArray objectAtIndex:0] CGPointValue];
        UILabel *graduationLabel = [[UILabel alloc] initWithFrame:CGRectMake(labelPoint.x-_lengthUnit, labelPoint.y-_lengthUnit*5/8, _lengthUnit*5/8, _lengthUnit)];
        graduationLabel.adjustsFontSizeToFitWidth = YES;
        graduationLabel.tag = labelTag;
        graduationLabel.font = [UIFont systemFontOfSize:ceil(_lengthUnit)];
        graduationLabel.textColor = [UIColor orangeColor];
        graduationLabel.text = [NSString stringWithFormat:@"%.0f",_valueDivider*section];
        [self addSubview:graduationLabel];
        if (_isShowGraduation) {
            [graduationLabel setHidden:NO];
        }else{
            [graduationLabel setHidden:YES];}
    }
 
}
 
- (NSArray *)getWebPointWithLength:(CGFloat)length angleArray:(NSArray *)angleArray {
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSNumber *angleNumber in angleArray) {
        CGFloat angle = [angleNumber floatValue];
        CGFloat x = _centerX + length*cos(angle);
        CGFloat y = _centerY + length*sin(angle);
        [pointArray addObject:[NSValue valueWithCGPoint:CGPointMake(x,y)]];
    }
    return pointArray;
    
}
 
- (NSArray *)getLengthArrayWithCircleNum:(int)plotCircles {
    NSMutableArray *lengthArray = [NSMutableArray array];
    CGFloat length = 0;
    for (int i = 0; i < plotCircles; i++) {
        length += _lengthUnit;
        [lengthArray addObject:[NSNumber numberWithFloat:length]];
    }
    return lengthArray;
}
 
- (CGFloat)getMaxWidthLabelFromArray:(NSArray *)keyArray withFontSize:(CGFloat)size {
    CGFloat maxWidth = 0;
    for (NSString *str in keyArray) {
        CGSize detailSize = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_fontSize]}];
        maxWidth = MAX(maxWidth, detailSize.width);
    }
    return maxWidth;
}
 
- (CGFloat)getMaxValueFromArray:(NSArray *)valueArray {
    CGFloat max = _maxValue;
    for (NSNumber *valueNum in valueArray) {
        CGFloat valueFloat = [valueNum floatValue];
        max = MAX(valueFloat, max);
    }
    return ceil(max);
}
 
- (void)addAnimationIfNeeded
{
    if (self.displayAnimated) {
        CABasicAnimation *animateScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animateScale.fromValue = [NSNumber numberWithFloat:0.f];
        animateScale.toValue = [NSNumber numberWithFloat:1.0f];
        
        CABasicAnimation *animateMove = [CABasicAnimation animationWithKeyPath:@"position"];
        animateMove.fromValue = [NSValue valueWithCGPoint:CGPointMake(_centerX, _centerY)];
        animateMove.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
        
        CABasicAnimation *animateAlpha = [CABasicAnimation animationWithKeyPath:@"opacity"];
        animateAlpha.fromValue = [NSNumber numberWithFloat:0.f];
        
        CAAnimationGroup *aniGroup = [CAAnimationGroup animation];
        aniGroup.duration = 1.f;
        aniGroup.repeatCount = 1;
        aniGroup.animations = [NSArray arrayWithObjects:animateScale,animateMove,animateAlpha, nil];
        aniGroup.removedOnCompletion = YES;
        
        [_chartPlot addAnimation:aniGroup forKey:nil];
    }
}
 
@end