forked from philackm/ScrollableGraphView
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ScrollableGraphView.swift
1997 lines (1533 loc) · 75.4 KB
/
ScrollableGraphView.swift
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
import UIKit
// MARK: - ScrollableGraphView
@IBDesignable
@objc open class ScrollableGraphView: UIScrollView, UIScrollViewDelegate, ScrollableGraphViewDrawingDelegate {
// MARK: - Public Properties
// Use these to customise the graph.
// #################################
// Line Styles
// ###########
/// Specifies how thick the graph of the line is. In points.
@IBInspectable open var lineWidth: CGFloat = 2
/// The color of the graph line. UIColor.
// We must not use type inferring here or else the property won't show up in IB
@IBInspectable open var lineColor: UIColor = UIColor.black
@IBInspectable var lineStyle_: Int {
get { return lineStyle.rawValue }
set {
if let enumValue = ScrollableGraphViewLineStyle(rawValue: newValue) {
lineStyle = enumValue
}
}
}
/// Whether or not the line should be rendered using bezier curves are straight lines.
open var lineStyle = ScrollableGraphViewLineStyle.straight
/// How each segment in the line should connect. Takes any of the Core Animation LineJoin values.
@IBInspectable open var lineJoin: String = kCALineJoinRound
/// The line caps. Takes any of the Core Animation LineCap values.
@IBInspectable open var lineCap: String = kCALineCapRound
@IBInspectable open var lineCurviness: CGFloat = 0.5
// Bar styles
// ##########
/// Whether bars should be drawn or not. If you want a bar graph, this should be set to true.
@IBInspectable open var shouldDrawBarLayer: Bool = false
/// The width of an individual bar on the graph.
@IBInspectable open var barWidth: CGFloat = 25;
/// The actual colour of the bar.
@IBInspectable open var barColor: UIColor = UIColor.gray
/// The width of the outline of the bar
@IBInspectable open var barLineWidth: CGFloat = 1
/// The colour of the bar outline
@IBInspectable open var barLineColor: UIColor = UIColor.darkGray
/// Whether the bars should be drawn with rounded corners
@IBInspectable open var shouldRoundBarCorners: Bool = false
// Fill Styles
// ###########
/// The background colour for the entire graph view, not just the plotted graph.
@IBInspectable open var backgroundFillColor: UIColor = UIColor.white
/// Specifies whether or not the plotted graph should be filled with a colour or gradient.
@IBInspectable open var shouldFill: Bool = false
@IBInspectable var fillType_: Int {
get { return fillType.rawValue }
set {
if let enumValue = ScrollableGraphViewFillType(rawValue: newValue) {
fillType = enumValue
}
}
}
/// Specifies whether to fill the graph with a solid colour or gradient.
open var fillType = ScrollableGraphViewFillType.solid
/// If fillType is set to .Solid then this colour will be used to fill the graph.
@IBInspectable open var fillColor: UIColor = UIColor.black
/// If fillType is set to .Gradient then this will be the starting colour for the gradient.
@IBInspectable open var fillGradientStartColor: UIColor = UIColor.white
/// If fillType is set to .Gradient, then this will be the ending colour for the gradient.
@IBInspectable open var fillGradientEndColor: UIColor = UIColor.black
@IBInspectable var fillGradientType_: Int {
get { return fillGradientType.rawValue }
set {
if let enumValue = ScrollableGraphViewGradientType(rawValue: newValue) {
fillGradientType = enumValue
}
}
}
/// If fillType is set to .Gradient, then this defines whether the gradient is rendered as a linear gradient or radial gradient.
open var fillGradientType = ScrollableGraphViewGradientType.linear
// Spacing
// #######
/// How far the "maximum" reference line is from the top of the view's frame. In points.
@IBInspectable open var topMargin: CGFloat = 10
/// How far the "minimum" reference line is from the bottom of the view's frame. In points.
@IBInspectable open var bottomMargin: CGFloat = 10
/// How far the first point on the graph should be placed from the left hand side of the view.
@IBInspectable open var leftmostPointPadding: CGFloat = 50
/// How far the final point on the graph should be placed from the right hand side of the view.
@IBInspectable open var rightmostPointPadding: CGFloat = 50
/// How much space should be between each data point.
@IBInspectable open var dataPointSpacing: CGFloat = 40
@IBInspectable var direction_: Int {
get { return direction.rawValue }
set {
if let enumValue = ScrollableGraphViewDirection(rawValue: newValue) {
direction = enumValue
}
}
}
/// Which side of the graph the user is expected to scroll from.
open var direction = ScrollableGraphViewDirection.leftToRight
// Graph Range
// ###########
/// If this is set to true, then the range will automatically be detected from the data the graph is given.
@IBInspectable open var shouldAutomaticallyDetectRange: Bool = false
/// Forces the graph's minimum to always be zero. Used in conjunction with shouldAutomaticallyDetectRange or shouldAdaptRange, if you want to force the minimum to stay at 0 rather than the detected minimum.
@IBInspectable open var shouldRangeAlwaysStartAtZero: Bool = false // Used in conjunction with shouldAutomaticallyDetectRange, if you want to force the min to stay at 0.
/// The minimum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMin: Double = 0
/// The maximum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMax: Double = 100
// Data Point Drawing
// ##################
/// Whether or not to draw a symbol for each data point.
@IBInspectable open var shouldDrawDataPoint: Bool = true
/// The shape to draw for each data point.
open var dataPointType = ScrollableGraphViewDataPointType.circle
/// The size of the shape to draw for each data point.
@IBInspectable open var dataPointSize: CGFloat = 5
/// The colour with which to fill the shape.
@IBInspectable open var dataPointFillColor: UIColor = UIColor.black
/// If dataPointType is set to .Custom then you,can provide a closure to create any kind of shape you would like to be displayed instead of just a circle or square. The closure takes a CGPoint which is the centre of the shape and it should return a complete UIBezierPath.
open var customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)?
// Adapting & Animations
// #####################
/// Whether or not the y-axis' range should adapt to the points that are visible on screen. This means if there are only 5 points visible on screen at any given time, the maximum on the y-axis will be the maximum of those 5 points. This is updated automatically as the user scrolls along the graph.
@IBInspectable open var shouldAdaptRange: Bool = false
/// If shouldAdaptRange is set to true then this specifies whether or not the points on the graph should animate to their new positions. Default is set to true.
@IBInspectable open var shouldAnimateOnAdapt: Bool = true
/// How long the animation should take. Affects both the startup animation and the animation when the range of the y-axis adapts to onscreen points.
@IBInspectable open var animationDuration: Double = 1
@IBInspectable var adaptAnimationType_: Int {
get { return adaptAnimationType.rawValue }
set {
if let enumValue = ScrollableGraphViewAnimationType(rawValue: newValue) {
adaptAnimationType = enumValue
}
}
}
/// The animation style.
open var adaptAnimationType = ScrollableGraphViewAnimationType.easeOut
/// If adaptAnimationType is set to .Custom, then this is the easing function you would like applied for the animation.
open var customAnimationEasingFunction: ((_ t: Double) -> Double)?
/// Whether or not the graph should animate to their positions when the graph is first displayed.
@IBInspectable open var shouldAnimateOnStartup: Bool = true
// Reference Lines
// ###############
/// Whether or not to show the y-axis reference lines and labels.
@IBInspectable open var shouldShowReferenceLines: Bool = true
/// The colour for the reference lines.
@IBInspectable open var referenceLineColor: UIColor = UIColor.black
/// The thickness of the reference lines.
@IBInspectable open var referenceLineThickness: CGFloat = 0.5
@IBInspectable var referenceLinePosition_: Int {
get { return referenceLinePosition.rawValue }
set {
if let enumValue = ScrollableGraphViewReferenceLinePosition(rawValue: newValue) {
referenceLinePosition = enumValue
}
}
}
/// Where the labels should be displayed on the reference lines.
open var referenceLinePosition = ScrollableGraphViewReferenceLinePosition.left
/// The type of reference lines. Currently only .Cover is available.
open var referenceLineType = ScrollableGraphViewReferenceLineType.cover
/// How many reference lines should be between the minimum and maximum reference lines. If you want a total of 4 reference lines, you would set this to 2. This can be set to 0 for no intermediate reference lines.This can be used to create reference lines at specific intervals. If the desired result is to have a reference line at every 10 units on the y-axis, you could, for example, set rangeMax to 100, rangeMin to 0 and numberOfIntermediateReferenceLines to 9.
@IBInspectable open var numberOfIntermediateReferenceLines: Int = 3
/// Whether or not to add labels to the intermediate reference lines.
@IBInspectable open var shouldAddLabelsToIntermediateReferenceLines: Bool = true
/// Whether or not to add units specified by the referenceLineUnits variable to the labels on the intermediate reference lines.
@IBInspectable open var shouldAddUnitsToIntermediateReferenceLineLabels: Bool = false
// Reference Line Labels
// #####################
/// The font to be used for the reference line labels.
open var referenceLineLabelFont = UIFont.systemFont(ofSize: 8)
/// The colour of the reference line labels.
@IBInspectable open var referenceLineLabelColor: UIColor = UIColor.black
/// Whether or not to show the units on the reference lines.
@IBInspectable open var shouldShowReferenceLineUnits: Bool = true
/// The units that the y-axis is in. This string is used for labels on the reference lines.
@IBInspectable open var referenceLineUnits: String?
/// The number of decimal places that should be shown on the reference line labels.
@IBInspectable open var referenceLineNumberOfDecimalPlaces: Int = 0
/// The NSNumberFormatterStyle that reference lines should use to display
@IBInspectable open var referenceLineNumberStyle: NumberFormatter.Style = .none
// Data Point Labels
// #################
/// Whether or not to show the labels on the x-axis for each point.
@IBInspectable open var shouldShowLabels: Bool = true
/// How far from the "minimum" reference line the data point labels should be rendered.
@IBInspectable open var dataPointLabelTopMargin: CGFloat = 10
/// How far from the bottom of the view the data point labels should be rendered.
@IBInspectable open var dataPointLabelBottomMargin: CGFloat = 0
/// The font for the data point labels.
@IBInspectable open var dataPointLabelColor: UIColor = UIColor.black
/// The colour for the data point labels.
open var dataPointLabelFont: UIFont? = UIFont.systemFont(ofSize: 10)
/// Used to force the graph to show every n-th dataPoint label
@IBInspectable open var dataPointLabelsSparsity: Int = 1
// MARK: - Private State
// #####################
// Graph Data for Display
private var data = [Double]()
private var labels = [String]()
private var isInitialSetup = true
private var dataNeedsReloading = true
private var isCurrentlySettingUp = false
private var viewportWidth: CGFloat = 0 {
didSet { if(oldValue != viewportWidth) { viewportDidChange() }}
}
private var viewportHeight: CGFloat = 0 {
didSet { if(oldValue != viewportHeight) { viewportDidChange() }}
}
private var totalGraphWidth: CGFloat = 0
private var offsetWidth: CGFloat = 0
// Graph Line
private var currentLinePath = UIBezierPath()
private var zeroYPosition: CGFloat = 0
// Labels
private var labelsView = UIView()
private var labelPool = LabelPool()
// Graph Drawing
private var graphPoints = [GraphPoint]()
private var drawingView = UIView()
private var barLayer: BarDrawingLayer?
private var lineLayer: LineDrawingLayer?
private var dataPointLayer: DataPointDrawingLayer?
private var fillLayer: FillDrawingLayer?
private var gradientLayer: GradientDrawingLayer?
// Reference Lines
private var referenceLineView: ReferenceLineDrawingView?
// Animation
private var displayLink: CADisplayLink!
private var previousTimestamp: CFTimeInterval = 0
private var currentTimestamp: CFTimeInterval = 0
private var currentAnimations = [GraphPointAnimation]()
// Active Points & Range Calculation
private var previousActivePointsInterval: CountableRange<Int> = -1 ..< -1
private var activePointsInterval: CountableRange<Int> = -1 ..< -1 {
didSet {
if(oldValue.lowerBound != activePointsInterval.lowerBound || oldValue.upperBound != activePointsInterval.upperBound) {
if !isCurrentlySettingUp { activePointsDidChange() }
}
}
}
private var range: (min: Double, max: Double) = (0, 100) {
didSet {
if(oldValue.min != range.min || oldValue.max != range.max) {
if !isCurrentlySettingUp { rangeDidChange() }
}
}
}
// MARK: - INIT, SETUP & VIEWPORT RESIZING
// #######################################
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
displayLink?.invalidate()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
set(data: [10, 2, 34, 11, 22, 11, 44, 9, 12, 4], withLabels: ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"])
}
private func setup() {
isCurrentlySettingUp = true
// Make sure everything is in a clean state.
reset()
// Calculate the viewport and drawing frames.
self.viewportWidth = self.frame.width
self.viewportHeight = self.frame.height
totalGraphWidth = graphWidth(forNumberOfDataPoints: data.count)
self.contentSize = CGSize(width: totalGraphWidth, height: viewportHeight)
// Scrolling direction.
#if TARGET_INTERFACE_BUILDER
self.offsetWidth = 0
#else
if (direction == .rightToLeft) {
self.offsetWidth = self.contentSize.width - viewportWidth
}
// Otherwise start of all the way to the left.
else {
self.offsetWidth = 0
}
#endif
// Set the scrollview offset.
self.contentOffset.x = self.offsetWidth
// Calculate the initial range depending on settings.
let initialActivePointsInterval = calculateActivePointsInterval()
let detectedRange = calculateRange(forEntireDataset: self.data)
if(shouldAutomaticallyDetectRange) {
self.range = detectedRange
}
else {
self.range = (min: rangeMin, max: rangeMax)
}
if (shouldAdaptRange) { // This supercedes the shouldAutomaticallyDetectRange option
let range = calculateRange(forActivePointsInterval: initialActivePointsInterval)
self.range = range
}
// If the graph was given all 0s as data, we can't use a range of 0->0, so make sure we have a sensible range at all times.
if (self.range.min == 0 && self.range.max == 0) {
self.range = (min: 0, max: rangeMax)
}
// DRAWING
let viewport = CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight)
// Create all the GraphPoints which which are used for drawing.
for i in 0 ..< data.count {
#if TARGET_INTERFACE_BUILDER
let value = data[i]
#else
let value = (shouldAnimateOnStartup) ? self.range.min : data[i]
#endif
let position = calculatePosition(atIndex: i, value: value)
let point = GraphPoint(position: position)
graphPoints.append(point)
}
// Drawing Layers
drawingView = UIView(frame: viewport)
drawingView.backgroundColor = backgroundFillColor
self.addSubview(drawingView)
addDrawingLayers(inViewport: viewport)
// References Lines
if(shouldShowReferenceLines) {
addReferenceLines(inViewport: viewport)
}
// X-Axis Labels
self.insertSubview(labelsView, aboveSubview: drawingView)
updateOffsetWidths()
#if !TARGET_INTERFACE_BUILDER
// Animation loop for when the range adapts
displayLink = CADisplayLink(target: self, selector: #selector(animationUpdate))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
displayLink.isPaused = true
#endif
isCurrentlySettingUp = false
// Set the first active points interval. These are the points that are visible when the view loads.
self.activePointsInterval = initialActivePointsInterval
}
// Makes sure everything is in a clean state for when we want to reset the data for a graph.
private func reset() {
drawingView.removeFromSuperview()
referenceLineView?.removeFromSuperview()
labelPool = LabelPool()
for labelView in labelsView.subviews {
labelView.removeFromSuperview()
}
graphPoints.removeAll()
currentAnimations.removeAll()
displayLink?.invalidate()
previousTimestamp = 0
currentTimestamp = 0
previousActivePointsInterval = -1 ..< -1
activePointsInterval = -1 ..< -1
range = (0, 100)
}
private func addDrawingLayers(inViewport viewport: CGRect) {
// Line Layer
lineLayer = LineDrawingLayer(frame: viewport, lineWidth: lineWidth, lineColor: lineColor, lineStyle: lineStyle, lineJoin: lineJoin, lineCap: lineCap)
lineLayer?.graphViewDrawingDelegate = self
drawingView.layer.addSublayer(lineLayer!)
// Data Point layer
if(shouldDrawDataPoint) {
dataPointLayer = DataPointDrawingLayer(frame: viewport, fillColor: dataPointFillColor, dataPointType: dataPointType, dataPointSize: dataPointSize, customDataPointPath: customDataPointPath)
dataPointLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(dataPointLayer!, above: lineLayer)
}
// Gradient and Fills
switch (self.fillType) {
case .solid:
if(shouldFill) {
// Setup fill
fillLayer = FillDrawingLayer(frame: viewport, fillColor: fillColor)
fillLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(fillLayer!, below: lineLayer)
}
case .gradient:
if(shouldFill) {
gradientLayer = GradientDrawingLayer(frame: viewport, startColor: fillGradientStartColor, endColor: fillGradientEndColor, gradientType: fillGradientType)
gradientLayer!.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer(gradientLayer!, below: lineLayer)
}
}
// The bar layer
if (shouldDrawBarLayer) {
// Bar Layer
barLayer = BarDrawingLayer(frame: viewport,
barWidth: barWidth,
barColor: barColor,
barLineWidth: barLineWidth,
barLineColor: barLineColor,
shouldRoundCorners: shouldRoundBarCorners)
barLayer?.graphViewDrawingDelegate = self
drawingView.layer.insertSublayer (barLayer!, below: lineLayer)
}
}
private func addReferenceLines(inViewport viewport: CGRect) {
var referenceLineBottomMargin = bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) {
referenceLineBottomMargin += (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin)
}
referenceLineView = ReferenceLineDrawingView(
frame: viewport,
topMargin: topMargin,
bottomMargin: referenceLineBottomMargin,
referenceLineColor: self.referenceLineColor,
referenceLineThickness: self.referenceLineThickness)
// Reference line settings.
referenceLineView?.referenceLinePosition = self.referenceLinePosition
referenceLineView?.referenceLineType = self.referenceLineType
referenceLineView?.numberOfIntermediateReferenceLines = self.numberOfIntermediateReferenceLines
// Reference line label settings.
referenceLineView?.shouldAddLabelsToIntermediateReferenceLines = self.shouldAddLabelsToIntermediateReferenceLines
referenceLineView?.shouldAddUnitsToIntermediateReferenceLineLabels = self.shouldAddUnitsToIntermediateReferenceLineLabels
referenceLineView?.labelUnits = referenceLineUnits
referenceLineView?.labelFont = self.referenceLineLabelFont
referenceLineView?.labelColor = self.referenceLineLabelColor
referenceLineView?.labelDecimalPlaces = self.referenceLineNumberOfDecimalPlaces
referenceLineView?.labelNumberStyle = self.referenceLineNumberStyle
referenceLineView?.set(range: self.range)
self.addSubview(referenceLineView!)
}
// If the view has changed we have to make sure we're still displaying the right data.
override open func layoutSubviews() {
super.layoutSubviews()
// while putting the view on the IB, we may get calls with frame too small
// if frame height is too small we won't be able to calculate zeroYPosition
// so make sure to proceed only if there is enough space
var availableGraphHeight = frame.height
availableGraphHeight = availableGraphHeight - topMargin - bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) { availableGraphHeight -= (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) }
if availableGraphHeight > 0 {
updateUI()
}
}
private func updateUI() {
// Make sure we have data, if don't, just get out. We can't do anything without any data.
guard data.count > 0 else {
return
}
// If the data has been updated, we need to re-init everything
if (dataNeedsReloading) {
setup()
if(shouldAnimateOnStartup) {
startAnimations(withStaggerValue: 0.15)
}
// We're done setting up.
dataNeedsReloading = false
isInitialSetup = false
}
// Otherwise, the user is just scrolling and we just need to update everything.
else {
// Needs to update the viewportWidth and viewportHeight which is used to calculate which
// points we can actually see.
viewportWidth = self.frame.width
viewportHeight = self.frame.height
// If the scrollview has scrolled anywhere, we need to update the offset
// and move around our drawing views.
offsetWidth = self.contentOffset.x
updateOffsetWidths()
// Recalculate active points for this size.
// Recalculate range for active points.
let newActivePointsInterval = calculateActivePointsInterval()
self.previousActivePointsInterval = self.activePointsInterval
self.activePointsInterval = newActivePointsInterval
// If adaption is enabled we want to
if(shouldAdaptRange) {
let newRange = calculateRange(forActivePointsInterval: newActivePointsInterval)
self.range = newRange
}
}
}
private func updateOffsetWidths() {
drawingView.frame.origin.x = offsetWidth
drawingView.bounds.origin.x = offsetWidth
gradientLayer?.offset = offsetWidth
referenceLineView?.frame.origin.x = offsetWidth
}
private func updateFrames() {
// Drawing view needs to always be the same size as the scrollview.
drawingView.frame.size.width = viewportWidth
drawingView.frame.size.height = viewportHeight
// Gradient should extend over the entire viewport
gradientLayer?.frame.size.width = viewportWidth
gradientLayer?.frame.size.height = viewportHeight
// Reference lines should extend over the entire viewport
referenceLineView?.set(viewportWidth: viewportWidth, viewportHeight: viewportHeight)
self.contentSize.height = viewportHeight
}
// MARK: - Public Methods
// ######################
open func set(data: [Double], withLabels labels: [String]) {
// If we are setting exactly the same data and labels, there's no need to re-init everything.
if(self.data == data && self.labels == labels) {
return
}
self.dataNeedsReloading = true
self.data = data
self.labels = labels
if(!isInitialSetup) {
updateUI()
}
}
// MARK: - Private Methods
// #######################
// MARK: Animation
// Animation update loop for co-domain changes.
@objc private func animationUpdate() {
let dt = timeSinceLastFrame()
for animation in currentAnimations {
animation.update(withTimestamp: dt)
if animation.finished {
dequeue(animation: animation)
}
}
updatePaths()
}
private func animate(point: GraphPoint, to position: CGPoint, withDelay delay: Double = 0) {
let currentPoint = CGPoint(x: point.x, y: point.y)
let animation = GraphPointAnimation(fromPoint: currentPoint, toPoint: position, forGraphPoint: point)
animation.animationEasing = getAnimationEasing()
animation.duration = animationDuration
animation.delay = delay
enqueue(animation: animation)
}
private func getAnimationEasing() -> (Double) -> Double {
switch(self.adaptAnimationType) {
case .elastic:
return Easings.easeOutElastic
case .easeOut:
return Easings.easeOutQuad
case .custom:
if let customEasing = customAnimationEasingFunction {
return customEasing
}
else {
fallthrough
}
default:
return Easings.easeOutQuad
}
}
private func enqueue(animation: GraphPointAnimation) {
if (currentAnimations.count == 0) {
// Need to kick off the loop.
displayLink.isPaused = false
}
currentAnimations.append(animation)
}
private func dequeue(animation: GraphPointAnimation) {
if let index = currentAnimations.index(of: animation) {
currentAnimations.remove(at: index)
}
if(currentAnimations.count == 0) {
// Stop animation loop.
displayLink.isPaused = true
}
}
private func dequeueAllAnimations() {
for animation in currentAnimations {
animation.animationDidFinish()
}
currentAnimations.removeAll()
displayLink.isPaused = true
}
private func timeSinceLastFrame() -> Double {
if previousTimestamp == 0 {
previousTimestamp = displayLink.timestamp
} else {
previousTimestamp = currentTimestamp
}
currentTimestamp = displayLink.timestamp
var dt = currentTimestamp - previousTimestamp
if dt > 0.032 {
dt = 0.032
}
return dt
}
// MARK: Layout Calculations
private func calculateActivePointsInterval() -> CountableRange<Int> {
// Calculate the "active points"
let min = Int((offsetWidth) / dataPointSpacing)
let max = Int(((offsetWidth + viewportWidth)) / dataPointSpacing)
// Add and minus two so the path goes "off the screen" so we can't see where it ends.
let minPossible = 0
let maxPossible = data.count - 1
let numberOfPointsOffscreen = 2
let actualMin = clamp(value: min - numberOfPointsOffscreen, min: minPossible, max: maxPossible)
let actualMax = clamp(value: max + numberOfPointsOffscreen, min: minPossible, max: maxPossible)
return actualMin..<actualMax.advanced(by: 1)
}
private func calculateRange(forActivePointsInterval interval: CountableRange<Int>) -> (min: Double, max: Double) {
let dataForActivePoints = data[interval]
// We don't have any active points, return defaults.
if(dataForActivePoints.count == 0) {
return (min: self.rangeMin, max: self.rangeMax)
}
else {
let range = calculateRange(for: dataForActivePoints)
return clean(range: range)
}
}
private func calculateRange(forEntireDataset data: [Double]) -> (min: Double, max: Double) {
let range = calculateRange(for: self.data)
return clean(range: range)
}
private func calculateRange<T: Collection>(for data: T) -> (min: Double, max: Double) where T.Iterator.Element == Double {
var rangeMin: Double = Double(Int.max)
var rangeMax: Double = Double(Int.min)
for dataPoint in data {
if (dataPoint > rangeMax) {
rangeMax = dataPoint
}
if (dataPoint < rangeMin) {
rangeMin = dataPoint
}
}
return (min: rangeMin, max: rangeMax)
}
private func clean(range: (min: Double, max: Double)) -> (min: Double, max: Double){
if(range.min == range.max) {
let min = shouldRangeAlwaysStartAtZero ? 0 : range.min
let max = range.max + 1
return (min: min, max: max)
}
else if (shouldRangeAlwaysStartAtZero) {
let min: Double = 0
var max: Double = range.max
// If we have all negative numbers and the max happens to be 0, there will cause a division by 0. Return the default height.
if(range.max == 0) {
max = rangeMax
}
return (min: min, max: max)
}
else {
return range
}
}
private func graphWidth(forNumberOfDataPoints numberOfPoints: Int) -> CGFloat {
let width: CGFloat = (CGFloat(numberOfPoints - 1) * dataPointSpacing) + (leftmostPointPadding + rightmostPointPadding)
return width
}
private func calculatePosition(atIndex index: Int, value: Double) -> CGPoint {
// Set range defaults based on settings:
// self.range.min/max is the current ranges min/max that has been detected
// self.rangeMin/Max is the min/max that should be used as specified by the user
let rangeMax = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.max : self.rangeMax
let rangeMin = (shouldAutomaticallyDetectRange || shouldAdaptRange) ? self.range.min : self.rangeMin
// y = the y co-ordinate in the view for the value in the graph
// ( ( value - max ) ) value = the value on the graph for which we want to know its corresponding location on the y axis in the view
// y = ( ( ----------- ) * graphHeight ) + topMargin t = the top margin
// ( ( min - max ) ) h = the height of the graph space without margins
// min = the range's current mininum
// max = the range's current maximum
// Calculate the position on in the view for the value specified.
var graphHeight = viewportHeight - topMargin - bottomMargin
if(shouldShowLabels && dataPointLabelFont != nil) { graphHeight -= (dataPointLabelFont!.pointSize + dataPointLabelTopMargin + dataPointLabelBottomMargin) }
let x = (CGFloat(index) * dataPointSpacing) + leftmostPointPadding
let y = (CGFloat((value - rangeMax) / (rangeMin - rangeMax)) * graphHeight) + topMargin
return CGPoint(x: x, y: y)
}
private func clamp<T: Comparable>(value:T, min:T, max:T) -> T {
if (value < min) {
return min
}
else if (value > max) {
return max
}
else {
return value
}
}
// MARK: Line Path Creation
@discardableResult
private func createLinePath() -> UIBezierPath {
currentLinePath.removeAllPoints()
let pathSegmentAdder = lineStyle == .straight ? addStraightLineSegment : addCurvedLineSegment
zeroYPosition = calculatePosition(atIndex: 0, value: self.range.min).y
// Connect the line to the starting edge if we are filling it.
if(shouldFill) {
// Add a line from the base of the graph to the first data point.
let firstDataPoint = graphPoints[activePointsInterval.lowerBound]
let viewportLeftZero = CGPoint(x: firstDataPoint.x - (leftmostPointPadding), y: zeroYPosition)
let leftFarEdgeTop = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: zeroYPosition)
let leftFarEdgeBottom = CGPoint(x: firstDataPoint.x - (leftmostPointPadding + viewportWidth), y: viewportHeight)
currentLinePath.move(to: leftFarEdgeBottom)
pathSegmentAdder(leftFarEdgeBottom, leftFarEdgeTop, currentLinePath)
pathSegmentAdder(leftFarEdgeTop, viewportLeftZero, currentLinePath)
pathSegmentAdder(viewportLeftZero, CGPoint(x: firstDataPoint.x, y: firstDataPoint.y), currentLinePath)
}
else {
let firstDataPoint = graphPoints[activePointsInterval.lowerBound]
currentLinePath.move(to: firstDataPoint.location)
}
// Connect each point on the graph with a segment.
for i in activePointsInterval.lowerBound ..< activePointsInterval.upperBound - 1 {
let startPoint = graphPoints[i].location
let endPoint = graphPoints[i+1].location
pathSegmentAdder(startPoint, endPoint, currentLinePath)
}
// Connect the line to the ending edge if we are filling it.
if(shouldFill) {
// Add a line from the last data point to the base of the graph.
let lastDataPoint = graphPoints[activePointsInterval.upperBound - 1]
let viewportRightZero = CGPoint(x: lastDataPoint.x + (rightmostPointPadding), y: zeroYPosition)
let rightFarEdgeTop = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: zeroYPosition)
let rightFarEdgeBottom = CGPoint(x: lastDataPoint.x + (rightmostPointPadding + viewportWidth), y: viewportHeight)
pathSegmentAdder(lastDataPoint.location, viewportRightZero, currentLinePath)
pathSegmentAdder(viewportRightZero, rightFarEdgeTop, currentLinePath)
pathSegmentAdder(rightFarEdgeTop, rightFarEdgeBottom, currentLinePath)
}
return currentLinePath
}
private func addStraightLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
path.addLine(to: endPoint)
}
private func addCurvedLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
// calculate control points
let difference = endPoint.x - startPoint.x
var x = startPoint.x + (difference * lineCurviness)
var y = startPoint.y
let controlPointOne = CGPoint(x: x, y: y)
x = endPoint.x - (difference * lineCurviness)
y = endPoint.y
let controlPointTwo = CGPoint(x: x, y: y)
// add curve from start to end
currentLinePath.addCurve(to: endPoint, controlPoint1: controlPointOne, controlPoint2: controlPointTwo)
}
// MARK: Events
// If the active points (the points we can actually see) change, then we need to update the path.
private func activePointsDidChange() {
let deactivatedPoints = determineDeactivatedPoints()
let activatedPoints = determineActivatedPoints()
updatePaths()
if(shouldShowLabels) {
let deactivatedLabelPoints = filterPointsForLabels(fromPoints: deactivatedPoints)
let activatedLabelPoints = filterPointsForLabels(fromPoints: activatedPoints)
updateLabels(deactivatedPoints: deactivatedLabelPoints, activatedPoints: activatedLabelPoints)
}
}
private func rangeDidChange() {
// If shouldAnimateOnAdapt is enabled it will kickoff any animations that need to occur.
startAnimations()
referenceLineView?.set(range: range)
}
private func viewportDidChange() {
// We need to make sure all the drawing views are the same size as the viewport.
updateFrames()
// Basically this recreates the paths with the new viewport size so things are in sync, but only
// if the viewport has changed after the initial setup. Because the initial setup will use the latest
// viewport anyway.
if(!isInitialSetup) {
updatePaths()
// Need to update the graph points so they are in their right positions for the new viewport.
// Animate them into position if animation is enabled, but make sure to stop any current animations first.
#if !TARGET_INTERFACE_BUILDER
dequeueAllAnimations()
#endif
startAnimations()
// The labels will also need to be repositioned if the viewport has changed.
repositionActiveLabels()
}
}
// Update any paths with the new path based on visible data points.
private func updatePaths() {
createLinePath()
if let drawingLayers = drawingView.layer.sublayers {
for layer in drawingLayers {
if let layer = layer as? ScrollableGraphViewDrawingLayer {
// The bar layer needs the zero Y position to set the bottom of the bar
layer.zeroYPosition = zeroYPosition
// Need to make sure this is set in createLinePath
assert (layer.zeroYPosition > 0);
layer.updatePath()
}
}
}
}
// Update any labels for any new points that have been activated and deactivated.
private func updateLabels(deactivatedPoints: [Int], activatedPoints: [Int]) {
// Disable any labels for the deactivated points.
for point in deactivatedPoints {
labelPool.activateLabel(forPointIndex: point)
}
// Grab an unused label and update it to the right position for the newly activated poitns
for point in activatedPoints {
let label = labelPool.activateLabel(forPointIndex: point)
label.text = (point < labels.count) ? labels[point] : ""
label.textColor = dataPointLabelColor
label.font = dataPointLabelFont
label.sizeToFit()