forked from Boris-Em/BEMSimpleLineGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBEMSimpleLineGraphView.m
More file actions
1478 lines (1235 loc) · 61.7 KB
/
BEMSimpleLineGraphView.m
File metadata and controls
1478 lines (1235 loc) · 61.7 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// BEMSimpleLineGraphView.m
// SimpleLineGraph
//
// Created by Bobo on 12/27/13. Updated by Sam Spencer on 1/11/14.
// Copyright (c) 2013 Boris Emorine. All rights reserved.
// Copyright (c) 2014 Sam Spencer.
//
#import "BEMSimpleLineGraphView.h"
#import "BEMGraphCalculator.h" //just for deprecation warnings; should be removed
#import "tgmath.h"
const CGFloat BEMNullGraphValue = CGFLOAT_MAX;
#if !__has_feature(objc_arc)
// Add the -fobjc-arc flag to enable ARC for only these files, as described in the ARC documentation: http://clang.llvm.org/docs/AutomaticReferenceCounting.html
#error BEMSimpleLineGraph is built with Objective-C ARC. You must enable ARC for these files.
#endif
typedef NS_ENUM(NSInteger, BEMInternalTags)
{
DotFirstTag100 = 100,
};
@interface BEMSimpleLineGraphView () {
/// The number of Points in the Graph
NSUInteger numberOfPoints;
/// All of the X-Axis Values
NSMutableArray <NSString *>*xAxisValues;
/// All of the X-Axis Label Points
NSMutableArray <NSNumber *>*xAxisLabelPoints;
/// How much to ??
CGFloat xAxisHorizontalFringeNegationValue;
/// All of the Y-Axis Label Points
NSMutableArray <NSNumber *> *yAxisLabelPoints;
/// All of the Y-Axis Values
NSMutableArray <NSNumber *>*yAxisValues;
/// All of the Data Points
NSMutableArray <NSNumber *> *dataPoints;
}
#pragma mark Properties to store all subviews
// Stores the background X Axis view
@property (strong, nonatomic ) UIView *backgroundXAxis;
// Stores the background Y Axis view
@property (strong, nonatomic) UIView *backgroundYAxis;
/// All of the Y-Axis Labels
@property (strong, nonatomic) NSMutableArray <UILabel *> *yAxisLabels;
/// All of the X-Axis Labels
@property (strong, nonatomic) NSMutableArray <UILabel *> *xAxisLabels;
/// All of the dataPoint Labels
@property (strong, nonatomic) NSMutableArray <UILabel *> *permanentPopups;
/// All of the dataPoint dots
@property (strong, nonatomic) NSMutableArray <BEMCircle *> *circleDots;
/// The line itself
@property (strong, nonatomic) BEMLine * masterLine;
/// The vertical line which appears when the user drags across the graph
@property (strong, nonatomic) UIView *touchInputLine;
/// View for picking up pan gesture
@property (strong, nonatomic, readwrite) UIView *panView;
/// Label to display when there is no data
@property (strong, nonatomic) UILabel *noDataLabel;
/// Cirle to display when there's only one datapoint
@property (strong, nonatomic) BEMCircle *oneDot;
/// The gesture recognizer picking up the pan in the graph view
@property (strong, nonatomic) UIPanGestureRecognizer *panGesture;
/// This gesture recognizer picks up the initial touch on the graph view
@property (strong, nonatomic) UILongPressGestureRecognizer *longPressGesture;
/// The label displayed when enablePopUpReport is set to YES
@property (strong, nonatomic) UILabel *popUpLabel;
// Possible custom View displayed instead of popUpLabel
@property (strong, nonatomic) UIView *customPopUpView;
#pragma mark calculated properties
/// The Y offset necessary to compensate the labels on the X-Axis
@property (nonatomic) CGFloat XAxisLabelYOffset;
/// The X offset necessary to compensate the labels on the Y-Axis. Will take the value of the bigger label on the Y-Axis
@property (nonatomic) CGFloat YAxisLabelXOffset;
/// The biggest value out of all of the data points
@property (nonatomic) CGFloat maxValue;
/// The smallest value out of all of the data points
@property (nonatomic) CGFloat minValue;
// Stores the current view size to detect whether a redraw is needed in layoutSubviews
@property (nonatomic) CGSize currentViewSize;
/// Find which point is currently the closest to the vertical line
- (BEMCircle *)closestDotFromTouchInputLine:(UIView *)touchInputLine;
@end
@implementation BEMSimpleLineGraphView
#pragma mark - Initialization
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) [self commonInit];
return self;
}
- (instancetype) initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) [self commonInit];
#define RestoreProperty(property, type) \
if ([coder containsValueForKey:@#property]) { \
self.property = [coder decode ## type ##ForKey:@#property]; \
}\
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullable-to-nonnull-conversion"
RestoreProperty (colorXaxisLabel, Object);
RestoreProperty (colorYaxisLabel, Object);
RestoreProperty (colorTop, Object);
RestoreProperty (colorLine, Object);
RestoreProperty (colorBottom, Object);
RestoreProperty (colorPoint, Object);
RestoreProperty (colorTouchInputLine, Object);
RestoreProperty (colorBackgroundPopUplabel, Object);
RestoreProperty (colorBackgroundYaxis, Object);
RestoreProperty (colorBackgroundXaxis, Object);
RestoreProperty (averageLine.color, Object);
RestoreProperty (alphaTop, Float);
RestoreProperty (alphaLine, Float);
RestoreProperty (alphaTouchInputLine, Float);
RestoreProperty (alphaBackgroundXaxis, Float);
RestoreProperty (alphaBackgroundYaxis, Float);
RestoreProperty (widthLine, Float);
RestoreProperty (widthReferenceLines, Float);
RestoreProperty (sizePoint, Float);
RestoreProperty (widthTouchInputLine, Float);
RestoreProperty (enableTouchReport, Bool);
RestoreProperty (enablePopUpReport, Bool);
RestoreProperty (enableBezierCurve, Bool);
RestoreProperty (enableXAxisLabel, Bool);
RestoreProperty (enableYAxisLabel, Bool);
RestoreProperty (autoScaleYAxis, Bool);
RestoreProperty (alwaysDisplayDots, Bool);
RestoreProperty (alwaysDisplayPopUpLabels, Bool);
RestoreProperty (enableLeftReferenceAxisFrameLine, Bool);
RestoreProperty (enableBottomReferenceAxisFrameLine, Bool);
RestoreProperty (interpolateNullValues, Bool);
RestoreProperty (displayDotsOnly, Bool);
RestoreProperty (displayDotsWhileAnimating, Bool);
RestoreProperty (touchReportFingersRequired, Int);
RestoreProperty (formatStringForValues, Object);
RestoreProperty (averageLine, Object);
return self;
#pragma clang diagnostic pop
}
- (void) encodeWithEncoder: (NSCoder *)coder {
#define EncodeProperty(property, type) [coder encode ## type: self.property forKey:@#property]
[super encodeWithCoder:coder];
EncodeProperty (labelFont, Object);
EncodeProperty (animationGraphEntranceTime, Float);
EncodeProperty (animationGraphStyle, Integer);
EncodeProperty (enableReferenceAxisFrame, Bool);
EncodeProperty (enableTopReferenceAxisFrameLine, Bool);
EncodeProperty (enableRightReferenceAxisFrameLine, Bool);
EncodeProperty (colorXaxisLabel, Object);
EncodeProperty (colorYaxisLabel, Object);
EncodeProperty (colorTop, Object);
EncodeProperty (colorLine, Object);
EncodeProperty (colorBottom, Object);
EncodeProperty (colorPoint, Object);
EncodeProperty (colorTouchInputLine, Object);
EncodeProperty (colorBackgroundPopUplabel, Object);
EncodeProperty (colorBackgroundYaxis, Object);
EncodeProperty (colorBackgroundXaxis, Object);
EncodeProperty (averageLine.color, Object);
EncodeProperty (alphaTop, Float);
EncodeProperty (alphaLine, Float);
EncodeProperty (alphaTouchInputLine, Float);
EncodeProperty (alphaBackgroundXaxis, Float);
EncodeProperty (alphaBackgroundYaxis, Float);
EncodeProperty (widthLine, Float);
EncodeProperty (widthReferenceLines, Float);
EncodeProperty (sizePoint, Float);
EncodeProperty (widthTouchInputLine, Float);
EncodeProperty (enableTouchReport, Bool);
EncodeProperty (enablePopUpReport, Bool);
EncodeProperty (enableBezierCurve, Bool);
EncodeProperty (enableXAxisLabel, Bool);
EncodeProperty (enableYAxisLabel, Bool);
EncodeProperty (autoScaleYAxis, Bool);
EncodeProperty (alwaysDisplayDots, Bool);
EncodeProperty (alwaysDisplayPopUpLabels, Bool);
EncodeProperty (enableLeftReferenceAxisFrameLine, Bool);
EncodeProperty (enableBottomReferenceAxisFrameLine, Bool);
EncodeProperty (enableTopReferenceAxisFrameLine, Bool);
EncodeProperty (enableRightReferenceAxisFrameLine, Bool);
EncodeProperty (interpolateNullValues, Bool);
EncodeProperty (displayDotsOnly, Bool);
EncodeProperty (displayDotsWhileAnimating, Bool);
[coder encodeInt: (int)(self.touchReportFingersRequired) forKey:@"touchReportFingersRequired"];
EncodeProperty (formatStringForValues, Object);
EncodeProperty (averageLine, Object);
}
- (void)commonInit {
// Do any initialization that's common to both -initWithFrame: and -initWithCoder: in this method
// Set the X Axis label font
_labelFont = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
// Set Animation Values
_animationGraphEntranceTime = 1.5;
// Set Color Values
_colorXaxisLabel = [UIColor blackColor];
_colorYaxisLabel = [UIColor blackColor];
_colorTop = [UIColor colorWithRed:0 green:122.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
_colorLine = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
_colorBottom = [UIColor colorWithRed:0 green:122.0f/255.0f blue:255.0f/255.0f alpha:1];
_colorPoint = [UIColor colorWithWhite:1.0f alpha:0.7f];
_colorTouchInputLine = [UIColor grayColor];
_colorBackgroundPopUplabel = [UIColor whiteColor];
_alphaTouchInputLine = 0.2f;
_widthTouchInputLine = 1.0;
_colorBackgroundXaxis = nil;
_alphaBackgroundXaxis = 1.0;
_colorBackgroundYaxis = nil;
_alphaBackgroundYaxis = 1.0;
_displayDotsWhileAnimating = YES;
// Set Alpha Values
_alphaTop = 1.0;
_alphaBottom = 1.0;
_alphaLine = 1.0;
// Set Size Values
_widthLine = 1.0;
_widthReferenceLines = 1.0;
_sizePoint = 10.0;
// Set Default Feature Values
_enableTouchReport = NO;
_touchReportFingersRequired = 1;
_enablePopUpReport = NO;
_enableBezierCurve = NO;
_enableXAxisLabel = YES;
_enableYAxisLabel = NO;
_YAxisLabelXOffset = 0;
_autoScaleYAxis = YES;
_alwaysDisplayDots = NO;
_alwaysDisplayPopUpLabels = NO;
_enableLeftReferenceAxisFrameLine = YES;
_enableBottomReferenceAxisFrameLine = YES;
_formatStringForValues = @"%.0f";
_interpolateNullValues = YES;
_displayDotsOnly = NO;
// Initialize the various arrays
xAxisValues = [NSMutableArray array];
xAxisLabelPoints = [NSMutableArray array];
yAxisValues = [NSMutableArray array];
yAxisLabelPoints = [NSMutableArray array];
dataPoints = [NSMutableArray array];
_xAxisLabels = [NSMutableArray array];
_yAxisLabels = [NSMutableArray array];
_permanentPopups = [NSMutableArray array];
_circleDots = [NSMutableArray array];
xAxisHorizontalFringeNegationValue = 0.0;
// Initialize BEM Objects
_averageLine = [[BEMAverageLine alloc] init];
}
- (void)drawGraph {
// Let the delegate know that the graph began layout updates
if ([self.delegate respondsToSelector:@selector(lineGraphDidBeginLoading:)])
[self.delegate lineGraphDidBeginLoading:self];
// Get the number of points in the graph
[self layoutNumberOfPoints];
if (numberOfPoints <= 1) {
return;
} else {
// Draw the graph
[self drawEntireGraph];
// Setup the touch report
[self layoutTouchReport];
// Let the delegate know that the graph finished updates
if ([self.delegate respondsToSelector:@selector(lineGraphDidFinishLoading:)])
[self.delegate lineGraphDidFinishLoading:self];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
if (CGSizeEqualToSize(self.currentViewSize, self.bounds.size)) return;
self.currentViewSize = self.bounds.size;
[self drawGraph];
}
-(void) clearGraph {
for (UIView * subvView in self.subviews) {
[subvView removeFromSuperview];
}
}
- (void)layoutNumberOfPoints {
// Get the total number of data points from the delegate
#ifndef TARGET_INTERFACE_BUILDER
if ([self.dataSource respondsToSelector:@selector(numberOfPointsInLineGraph:)]) {
numberOfPoints = [self.dataSource numberOfPointsInLineGraph:self];
} else {
numberOfPoints = 0;
}
#else
numberOfPoints = 10;
#endif
[self.noDataLabel removeFromSuperview];
[self.oneDot removeFromSuperview];
if (numberOfPoints == 0) {
// There are no points to load
[self clearGraph];
if (self.delegate &&
[self.delegate respondsToSelector:@selector(noDataLabelEnableForLineGraph:)] &&
![self.delegate noDataLabelEnableForLineGraph:self]) {
return;
}
NSLog(@"[BEMSimpleLineGraph] Data source contains no data. A no data label will be displayed and drawing will stop. Add data to the data source and then reload the graph.");
self.noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.viewForFirstBaselineLayout.frame.size.width, self.viewForFirstBaselineLayout.frame.size.height)];
self.noDataLabel.backgroundColor = [UIColor clearColor];
self.noDataLabel.textAlignment = NSTextAlignmentCenter;
NSString *noDataText = nil;
if ([self.delegate respondsToSelector:@selector(noDataLabelTextForLineGraph:)]) {
noDataText = [self.delegate noDataLabelTextForLineGraph:self];
}
self.noDataLabel.text = noDataText ?: NSLocalizedString(@"No Data", nil);
self.noDataLabel.font = self.noDataLabelFont ?: [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
self.noDataLabel.textColor = self.noDataLabelColor ?: (self.colorLine ?: [UIColor blackColor]);
[self.viewForFirstBaselineLayout addSubview:self.noDataLabel];
// Let the delegate know that the graph finished layout updates
if ([self.delegate respondsToSelector:@selector(lineGraphDidFinishLoading:)]) {
[self.delegate lineGraphDidFinishLoading:self];
}
} else if (numberOfPoints == 1) {
NSLog(@"[BEMSimpleLineGraph] Data source contains only one data point. Add more data to the data source and then reload the graph.");
[self clearGraph];
BEMCircle *circleDot = [[BEMCircle alloc] initWithFrame:CGRectMake(0, 0, self.sizePoint, self.sizePoint)];
circleDot.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
circleDot.color = self.colorPoint;
circleDot.alpha = 1.0f;
[self.viewForFirstBaselineLayout addSubview:circleDot];
self.oneDot = circleDot;
// Let the delegate know that the graph finished layout updates
if ([self.delegate respondsToSelector:@selector(lineGraphDidFinishLoading:)]) {
[self.delegate lineGraphDidFinishLoading:self];
}
}
}
- (void)layoutTouchReport {
// If the touch report is enabled, set it up
if (self.enableTouchReport == YES || self.enablePopUpReport == YES) {
// Initialize the vertical gray line that appears where the user touches the graph.
if (!self.touchInputLine) {
self.touchInputLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.widthTouchInputLine, self.frame.size.height)];
self.touchInputLine.backgroundColor = self.colorTouchInputLine;
self.touchInputLine.alpha = 0;
}
[self addSubview:self.touchInputLine];
if (!self.panView) {
self.panView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.viewForFirstBaselineLayout.frame.size.width, self.viewForFirstBaselineLayout.frame.size.height)];
self.panView.backgroundColor = [UIColor clearColor];
self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGestureAction:)];
self.panGesture.delegate = self;
[self.panGesture setMaximumNumberOfTouches:1];
[self.panView addGestureRecognizer:self.panGesture];
self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleGestureAction:)];
self.longPressGesture.minimumPressDuration = 0.1f;
[self.panView addGestureRecognizer:self.longPressGesture];
}
[self addSubview:self.panView];
}
}
#pragma mark - Drawing
- (void)didFinishDrawingIncludingYAxis:(BOOL)yAxisFinishedDrawing {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (self.animationGraphEntranceTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (self.enableYAxisLabel == NO) {
// Let the delegate know that the graph finished rendering
if ([self.delegate respondsToSelector:@selector(lineGraphDidFinishDrawing:)])
[self.delegate lineGraphDidFinishDrawing:self];
return;
} else {
if (yAxisFinishedDrawing == YES) {
// Let the delegate know that the graph finished rendering
if ([self.delegate respondsToSelector:@selector(lineGraphDidFinishDrawing:)])
[self.delegate lineGraphDidFinishDrawing:self];
return;
}
}
});
}
- (void)drawEntireGraph {
// The following method calls are in this specific order for a reason
// Changing the order of the method calls below can result in drawing glitches and even crashes
self.averageLine.yValue = NAN;
#ifndef TARGET_INTERFACE_BUILDER
self.maxValue = [self getMaximumValue];
self.minValue = [self getMinimumValue];
#else
self.minValue = 0.0f;
self.maxValue = 10000.0f;
#endif
// Set the Y-Axis Offset if the Y-Axis is enabled. The offset is relative to the size of the longest label on the Y-Axis.
if (self.enableYAxisLabel) {
self.YAxisLabelXOffset = 2.0f + [self calculateWidestLabel];
} else {
self.YAxisLabelXOffset = 0;
}
// Draw the X-Axis
[self drawXAxis];
// Draw the data points
[self drawDots];
// Draw line with bottom and top fill
[self drawLine];
// Draw the Y-Axis
[self drawYAxis];
}
-(CGFloat) labelWidthForValue:(CGFloat) value {
NSDictionary *attributes = @{NSFontAttributeName: self.labelFont};
NSString *valueString = [self yAxisTextForValue:value];
NSString *labelString = [valueString stringByReplacingOccurrencesOfString:@"[0-9-]" withString:@"N" options:NSRegularExpressionSearch range:NSMakeRange(0, [valueString length])];
return [labelString sizeWithAttributes:attributes].width;
}
- (CGFloat) calculateWidestLabel {
NSDictionary *attributes = @{NSFontAttributeName: self.labelFont};
CGFloat widestNumber;
if (self.autoScaleYAxis == YES){
widestNumber = MAX([self labelWidthForValue:self.maxValue],
[self labelWidthForValue:self.minValue]);
} else {
widestNumber = [self labelWidthForValue:self.frame.size.height] ;
}
return MAX(widestNumber, [self.averageLine.title sizeWithAttributes:attributes].width);
}
-(BEMCircle *) circleDotAtIndex:(NSUInteger) index forValue:(CGFloat) dotValue reuseNumber: (NSUInteger) reuseNumber {
CGFloat positionOnXAxis = numberOfPoints > 1 ?
(((self.frame.size.width - self.YAxisLabelXOffset) / (numberOfPoints - 1)) * index) :
self.frame.size.width/2;
if (self.positionYAxisRight == NO) {
positionOnXAxis += self.YAxisLabelXOffset;
}
CGFloat positionOnYAxis = [self yPositionForDotValue:dotValue];
[yAxisValues addObject:@(positionOnYAxis)];
if (dotValue >= BEMNullGraphValue) {
// If we're dealing with an null value, don't draw the dot (but put it in yAxis to interpolate line)
return nil;
}
BEMCircle *circleDot;
CGRect dotFrame = CGRectMake(0, 0, self.sizePoint, self.sizePoint);
if (reuseNumber < self.circleDots.count) {
circleDot = self.circleDots[reuseNumber];
circleDot.frame = dotFrame;
} else {
circleDot = [[BEMCircle alloc] initWithFrame:dotFrame];
[self.circleDots addObject:circleDot];
}
circleDot.center = CGPointMake(positionOnXAxis, positionOnYAxis);
circleDot.tag = (NSInteger) index + DotFirstTag100;
circleDot.absoluteValue = dotValue;
circleDot.color = self.colorPoint;
return circleDot;
}
- (void)drawDots {
// Remove all data points before adding them to the array
[dataPoints removeAllObjects];
// Remove all yAxis values before adding them to the array
[yAxisValues removeAllObjects];
// Loop through each point and add it to the graph
@autoreleasepool {
for (NSUInteger index = 0; index < numberOfPoints; index++) {
CGFloat dotValue = 0;
#ifndef TARGET_INTERFACE_BUILDER
if ([self.dataSource respondsToSelector:@selector(lineGraph:valueForPointAtIndex:)]) {
dotValue = [self.dataSource lineGraph:self valueForPointAtIndex:index];
} else {
[NSException raise:@"lineGraph:valueForPointAtIndex: protocol method is not implemented in the data source. Throwing exception here before the system throws a CALayerInvalidGeometry Exception." format:@"Value for point %f at index %lu is invalid. CALayer position may contain NaN: [0 nan]", dotValue, (unsigned long)index];
}
#else
dotValue = (int)(arc4random() % 10000);
#endif
[dataPoints addObject:@(dotValue)];
BEMCircle * circleDot = [self circleDotAtIndex: index forValue: dotValue reuseNumber: index];
UILabel * label = nil;
if (circleDot) {
[self addSubview:circleDot];
if (self.alwaysDisplayPopUpLabels == YES) {
if (![self.delegate respondsToSelector:@selector(lineGraph:alwaysDisplayPopUpAtIndex:)] ||
[self.delegate lineGraph:self alwaysDisplayPopUpAtIndex:index]) {
if (index < self.permanentPopups.count) {
label = self.permanentPopups[index];
} else {
label = [[UILabel alloc] initWithFrame:CGRectZero];
[self.permanentPopups addObject:label ];
}
label = [self configureLabel:label forPoint: circleDot ];
[self adjustXLocForLabel:label avoidingDot:circleDot.frame];
UILabel * leftNeighbor = (index >= 1 && self.permanentPopups[index-1].superview) ? self.permanentPopups[index-1] : nil;
UILabel * secondNeighbor = (index >= 2 && self.permanentPopups[index-2].superview) ? self.permanentPopups[index-2] : nil;
BOOL showLabel = [self adjustYLocForLabel:label
avoidingDot:circleDot.frame
andNeighbors:leftNeighbor.frame
and:secondNeighbor.frame ];
if (showLabel) {
[self addSubview:label];
} else {
[label removeFromSuperview];
}
}
}
// Dot and/or label entrance animation
circleDot.alpha = 0.0f;
label.alpha = 0.0f;
if (self.animationGraphEntranceTime <= 0) {
if (self.displayDotsOnly || self.alwaysDisplayDots ) {
circleDot.alpha = 1.0f;
}
label.alpha = 1.0f;
} else if (self.displayDotsWhileAnimating) {
[UIView animateWithDuration: self.animationGraphEntranceTime/numberOfPoints delay: index*(self.animationGraphEntranceTime/numberOfPoints) options:UIViewAnimationOptionCurveLinear animations:^{
circleDot.alpha = 1.0;
label.alpha = 1.0;
} completion:^(BOOL finished) {
if (self.alwaysDisplayDots == NO && self.displayDotsOnly == NO) {
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
circleDot.alpha = 0;
} completion:nil];
}
}];
} else if (label) {
[UIView animateWithDuration:0.5f delay:self.animationGraphEntranceTime options:UIViewAnimationOptionCurveLinear animations:^{
label.alpha = 1;
} completion:nil];
}
}
}
for (NSUInteger i = self.circleDots.count -1; i>=numberOfPoints; i--) {
[[self.permanentPopups lastObject] removeFromSuperview]; //no harm if not showing
[self.permanentPopups removeLastObject];
[[self.circleDots lastObject] removeFromSuperview];
[self.circleDots removeLastObject];
}
}
}
- (void)drawLine {
if (!self.masterLine) {
self.masterLine = [[BEMLine alloc] initWithFrame:[self drawableGraphArea]];
} else {
self.masterLine.frame = [self drawableGraphArea];
[self.masterLine setNeedsDisplay];
}
[self addSubview:self.masterLine];
BEMLine * line = self.masterLine;
line.opaque = NO;
line.alpha = 1;
line.backgroundColor = [UIColor clearColor];
line.topColor = self.colorTop;
line.bottomColor = self.colorBottom;
line.topAlpha = self.alphaTop;
line.bottomAlpha = self.alphaBottom;
line.topGradient = self.gradientTop;
line.bottomGradient = self.gradientBottom;
line.lineWidth = self.widthLine;
line.referenceLineWidth = self.widthReferenceLines > 0.0 ? self.widthReferenceLines : (self.widthLine/2);
line.lineAlpha = self.alphaLine;
line.bezierCurveIsEnabled = self.enableBezierCurve;
line.arrayOfPoints = yAxisValues;
line.arrayOfValues = self.graphValuesForDataPoints;
line.lineDashPatternForReferenceYAxisLines = self.lineDashPatternForReferenceYAxisLines;
line.lineDashPatternForReferenceXAxisLines = self.lineDashPatternForReferenceXAxisLines;
line.interpolateNullValues = self.interpolateNullValues;
line.enableReferenceFrame = self.enableReferenceAxisFrame;
line.enableRightReferenceFrameLine = self.enableRightReferenceAxisFrameLine;
line.enableTopReferenceFrameLine = self.enableTopReferenceAxisFrameLine;
line.enableLeftReferenceFrameLine = self.enableLeftReferenceAxisFrameLine;
line.enableBottomReferenceFrameLine = self.enableBottomReferenceAxisFrameLine;
if (self.enableReferenceXAxisLines || self.enableReferenceYAxisLines) {
line.enableReferenceLines = YES;
line.referenceLineColor = self.colorReferenceLines;
line.verticalReferenceHorizontalFringeNegation = xAxisHorizontalFringeNegationValue;
line.arrayOfVerticalReferenceLinePoints = self.enableReferenceXAxisLines ? xAxisLabelPoints : nil;
line.arrayOfHorizontalReferenceLinePoints = self.enableReferenceYAxisLines ? yAxisLabelPoints : nil;
}
line.color = self.colorLine;
line.lineGradient = self.gradientLine;
line.lineGradientDirection = self.gradientLineDirection;
line.animationTime = self.animationGraphEntranceTime;
line.animationType = self.animationGraphStyle;
if (self.averageLine.enableAverageLine == YES) {
if (isnan(self.averageLine.yValue)) self.averageLine.yValue = self.getAverageValue;
line.averageLineYCoordinate = [self yPositionForDotValue:self.averageLine.yValue];
}
line.averageLine = self.averageLine;
line.disableMainLine = self.displayDotsOnly;
[self sendSubviewToBack:line];
[self sendSubviewToBack:self.backgroundXAxis];
[self didFinishDrawingIncludingYAxis:NO];
}
- (void)drawXAxis {
if (!self.enableXAxisLabel) {
[self.backgroundXAxis removeFromSuperview];
self.backgroundXAxis = nil;
for (UILabel * label in self.xAxisLabels) {
[label removeFromSuperview];
}
self.xAxisLabels = [NSMutableArray array];
return;
}
if (![self.dataSource respondsToSelector:@selector(lineGraph:labelOnXAxisForIndex:)]) return;
[xAxisValues removeAllObjects];
[xAxisLabelPoints removeAllObjects];
xAxisHorizontalFringeNegationValue = 0.0;
// Draw X-Axis Background Area
if (!self.backgroundXAxis) {
self.backgroundXAxis = [[UIView alloc] initWithFrame:[self drawableXAxisArea]];
} else {
self.backgroundXAxis.frame = [self drawableXAxisArea];
}
[self addSubview:self.backgroundXAxis];
self.backgroundXAxis.backgroundColor = self.colorBackgroundXaxis ?: self.colorBottom;
self.backgroundXAxis.alpha = self.alphaBackgroundXaxis;
NSArray <NSNumber *> *axisIndices = nil;
if ([self.delegate respondsToSelector:@selector(incrementPositionsForXAxisOnLineGraph:)]) {
axisIndices = [self.delegate incrementPositionsForXAxisOnLineGraph:self];
} else {
NSUInteger baseIndex = 0;
NSUInteger increment = 1;
if ([self.delegate respondsToSelector:@selector(baseIndexForXAxisOnLineGraph:)] && [self.delegate respondsToSelector:@selector(incrementIndexForXAxisOnLineGraph:)]) {
baseIndex = [self.delegate baseIndexForXAxisOnLineGraph:self];
increment = [self.delegate incrementIndexForXAxisOnLineGraph:self];
} else if ([self.delegate respondsToSelector:@selector(numberOfGapsBetweenLabelsOnLineGraph:)]) {
increment = [self.delegate numberOfGapsBetweenLabelsOnLineGraph:self] + 1;
if (increment >= numberOfPoints -1) {
//need at least two points
baseIndex = 0;
increment = numberOfPoints - 1;
} else {
NSUInteger leftGap = increment - 1;
NSUInteger rightGap = numberOfPoints % increment;
NSUInteger offset = (leftGap-rightGap)/2;
baseIndex = increment - 1 - offset;
}
}
NSMutableArray <NSNumber *> *values = [NSMutableArray array ];
NSUInteger index = baseIndex;
while (index < numberOfPoints) {
[values addObject:@(index)];
index += increment;
}
axisIndices = [values copy];
}
NSUInteger xAxisLabelNumber = 0;
@autoreleasepool {
for (NSNumber *indexNum in axisIndices) {
NSUInteger index = indexNum.unsignedIntegerValue;
if (index > numberOfPoints) continue;
NSString *xAxisLabelText = [self xAxisTextForIndex:index];
UILabel *labelXAxis = [self xAxisLabelWithText:xAxisLabelText atIndex:index reuseNumber: xAxisLabelNumber];
[xAxisLabelPoints addObject:@(labelXAxis.center.x - (self.positionYAxisRight ? 0.0f : self.YAxisLabelXOffset))];
[self addSubview:labelXAxis];
[xAxisValues addObject:xAxisLabelText];
xAxisLabelNumber++;
}
}
for (NSUInteger i = self.xAxisLabels.count ; i>xAxisLabelNumber; i--) {
[[self.xAxisLabels lastObject] removeFromSuperview];
[self.xAxisLabels removeLastObject];
}
__block UILabel *prevLabel;
NSMutableArray <UILabel *> *overlapLabels = [NSMutableArray arrayWithCapacity:self.xAxisLabels.count];
[self.xAxisLabels enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL *stop) {
if (idx == 0) {
prevLabel = label; //always show first label
} else if (label.superview) { //only look at active labels
if (CGRectIsNull(CGRectIntersection(prevLabel.frame, label.frame)) &&
CGRectContainsRect(self.backgroundXAxis.frame, label.frame)) {
prevLabel = label; //no overlap and inside frame, so show this one
} else {
// NSLog(@"Not showing %@ due to %@; label: %@, width: %@ prevLabel: %@, frame: %@",
// label.text,
// CGRectIsNull(CGRectIntersection(prevLabel.frame, label.frame)) ?@"Overlap" : @"Out of bounds",
// NSStringFromCGRect(label.frame),
// @(CGRectGetMaxX(label.frame)),
// NSStringFromCGRect(prevLabel.frame),
// NSStringFromCGRect(self.backgroundXAxis.frame));
[overlapLabels addObject:label]; // Overlapped
}
}
}];
for (UILabel *l in overlapLabels) {
[l removeFromSuperview];
}
}
- (NSString *)xAxisTextForIndex:(NSUInteger)index {
NSString *xAxisLabelText = @"";
if ([self.dataSource respondsToSelector:@selector(lineGraph:labelOnXAxisForIndex:)]) {
xAxisLabelText = [self.dataSource lineGraph:self labelOnXAxisForIndex:index];
} else {
xAxisLabelText = @"";
}
return xAxisLabelText;
}
- (UILabel *)xAxisLabelWithText:(NSString *)text atIndex:(NSUInteger)index reuseNumber:(NSUInteger) xAxisLabelNumber{
UILabel *labelXAxis;
if (xAxisLabelNumber < self.xAxisLabels.count) {
labelXAxis = self.xAxisLabels[xAxisLabelNumber];
} else {
labelXAxis = [[UILabel alloc] init];
[self.xAxisLabels addObject:labelXAxis];
}
labelXAxis.text = text;
labelXAxis.font = self.labelFont;
labelXAxis.textAlignment = 1;
labelXAxis.textColor = self.colorXaxisLabel;
labelXAxis.backgroundColor = [UIColor clearColor];
// Add support multi-line, but this might overlap with the graph line if text have too many lines
labelXAxis.numberOfLines = 0;
CGRect lRect = [labelXAxis.text boundingRectWithSize:self.viewForFirstBaselineLayout.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:labelXAxis.font} context:nil];
// Determine the horizontal translation to perform on the far left and far right labels
// This property is negated when calculating the position of reference frames
CGFloat horizontalTranslation = 0;
if (index == 0) {
horizontalTranslation = lRect.size.width/2;
} else if (index+1 == numberOfPoints) {
horizontalTranslation = -lRect.size.width/2;
}
xAxisHorizontalFringeNegationValue = horizontalTranslation;
// Determine the final x-axis position
CGFloat positionOnXAxis = (((self.frame.size.width - self.YAxisLabelXOffset) / (numberOfPoints - 1)) * index) + horizontalTranslation;
if (!self.positionYAxisRight) {
positionOnXAxis += self.YAxisLabelXOffset;
}
labelXAxis.frame = lRect;
labelXAxis.center = CGPointMake(positionOnXAxis, self.frame.size.height - lRect.size.height/2.0f-1.0f);
return labelXAxis;
}
-(NSString *) yAxisTextForValue:(CGFloat) value {
NSString *yAxisSuffix = @"";
NSString *yAxisPrefix = @"";
if ([self.delegate respondsToSelector:@selector(yAxisPrefixOnLineGraph:)]) yAxisPrefix = [self.delegate yAxisPrefixOnLineGraph:self];
if ([self.delegate respondsToSelector:@selector(yAxisSuffixOnLineGraph:)]) yAxisSuffix = [self.delegate yAxisSuffixOnLineGraph:self];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
NSString *formattedValue = [NSString stringWithFormat:self.formatStringForValues, value];
#pragma clang diagnostic pop
return [NSString stringWithFormat:@"%@%@%@", yAxisPrefix, formattedValue, yAxisSuffix];
}
- (UILabel *)yAxisLabelWithText:(NSString *)text atValue:(CGFloat)value reuseNumber:(NSUInteger) reuseNumber {
//provide a Y-Axis Label with text at Value, reusing reuseNumber'd label if it exists
//special case: use self.Averageline.label if reuseNumber = NSIntegerMax
CGFloat labelHeight = self.labelFont.pointSize + 7.0f;
CGRect frameForLabelYAxis = CGRectMake(1.0f, 0.0f, self.YAxisLabelXOffset - 1.0f, labelHeight);
CGFloat xValueForCenterLabelYAxis = (self.YAxisLabelXOffset-1.0f) /2.0f;
NSTextAlignment textAlignmentForLabelYAxis = NSTextAlignmentRight;
if (self.positionYAxisRight) {
frameForLabelYAxis.origin = CGPointMake(self.frame.size.width - self.YAxisLabelXOffset - 1.0f, 0.0f);
xValueForCenterLabelYAxis = self.frame.size.width - xValueForCenterLabelYAxis-2.0f;
}
UILabel *labelYAxis;
if ( reuseNumber == NSIntegerMax) {
if (!self.averageLine.label) {
self.averageLine.label = [[UILabel alloc] initWithFrame:frameForLabelYAxis];
}
labelYAxis = self.averageLine.label;
} else if (reuseNumber < self.yAxisLabels.count) {
labelYAxis = self.yAxisLabels[reuseNumber];
} else {
labelYAxis = [[UILabel alloc] initWithFrame:frameForLabelYAxis];
[self.yAxisLabels addObject:labelYAxis];
}
labelYAxis.frame = frameForLabelYAxis;
labelYAxis.text = text;
labelYAxis.textAlignment = textAlignmentForLabelYAxis;
labelYAxis.font = self.labelFont;
labelYAxis.textColor = self.colorYaxisLabel;
labelYAxis.backgroundColor = [UIColor clearColor];
CGFloat yAxisPosition = [self yPositionForDotValue:value];
labelYAxis.center = CGPointMake(xValueForCenterLabelYAxis, yAxisPosition);
NSNumber *yAxisLabelCoordinate = @(labelYAxis.center.y);
[yAxisLabelPoints addObject:yAxisLabelCoordinate];
return labelYAxis;
}
- (void)drawYAxis {
if (!self.enableYAxisLabel) {
[self.backgroundYAxis removeFromSuperview];
self.backgroundYAxis = nil;
[self.averageLine.label removeFromSuperview];
self.averageLine.label = nil;
for (UILabel * label in self.yAxisLabels) {
[label removeFromSuperview];
}
self.yAxisLabels = [NSMutableArray array];
return;
}
//Make Background for Y Axis
CGRect frameForBackgroundYAxis = CGRectMake(
(self.positionYAxisRight ?
self.frame.size.width - self.YAxisLabelXOffset - 1.0f:
0.0),
0,
self.YAxisLabelXOffset - 1.0f,
self.frame.size.height);
if (!self.backgroundYAxis) {
self.backgroundYAxis= [[UIView alloc] initWithFrame:frameForBackgroundYAxis];
} else {
self.backgroundYAxis.frame = frameForBackgroundYAxis;
}
[self addSubview:self.backgroundYAxis];
self.backgroundYAxis.backgroundColor = self.colorBackgroundYaxis ?: self.colorTop;
self.backgroundYAxis.alpha = self.alphaBackgroundYaxis;
[yAxisLabelPoints removeAllObjects];
NSUInteger numberOfLabels = 3;
if ([self.delegate respondsToSelector:@selector(numberOfYAxisLabelsOnLineGraph:)]) {
numberOfLabels = [self.delegate numberOfYAxisLabelsOnLineGraph:self];
if (numberOfLabels <= 0) return;
}
//Now calculate baseValue and increment for all scenarios
CGFloat value;
CGFloat increment;
if (self.autoScaleYAxis) {
// Plot according to min-max range
if (numberOfLabels == 1) {
value = (self.minValue + self.maxValue)/2.0f;
increment = 0; //NA
} else {
value = self.minValue;
increment = (self.maxValue - self.minValue)/(numberOfLabels-1);
if ([self.delegate respondsToSelector:@selector(baseValueForYAxisOnLineGraph:)] && [self.delegate respondsToSelector:@selector(incrementValueForYAxisOnLineGraph:)]) {
value = [self.delegate baseValueForYAxisOnLineGraph:self];
increment = [self.delegate incrementValueForYAxisOnLineGraph:self];
numberOfLabels = (NSUInteger) ((self.maxValue - value)/increment)+1;
if (numberOfLabels > 100) {
NSLog(@"[BEMSimpleLineGraph] Increment does not properly lay out Y axis, bailing early");
return;
}
}
}
} else {
//not AutoScale
CGFloat graphHeight = self.frame.size.height - self.XAxisLabelYOffset;
if (numberOfLabels == 1) {
value = graphHeight/2.0f;
increment = 0; //NA
} else {
increment = graphHeight / numberOfLabels;
value = increment/2;
}
}
NSMutableArray <NSNumber *> *dotValues = [[NSMutableArray alloc] initWithCapacity:numberOfLabels];
for (NSUInteger i = 0; i < numberOfLabels; i++) {
[dotValues addObject:@(value)];
value += increment;
}
NSUInteger yAxisLabelNumber = 0;
@autoreleasepool {
for (NSNumber *dotValueNum in dotValues) {
CGFloat dotValue = dotValueNum.floatValue;
NSString *labelText = [self yAxisTextForValue:dotValue];
UILabel *labelYAxis = [self yAxisLabelWithText:labelText