-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
ChartViewBase.swift
executable file
·967 lines (795 loc) · 34.6 KB
/
ChartViewBase.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
//
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import UIKit
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
}
public class ChartViewBase: UIView, ChartDataProvider, ChartAnimatorDelegate
{
// MARK: - Properties
/// the default value formatter
internal var _defaultValueFormatter: NSNumberFormatter = ChartUtils.defaultValueFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData?
/// Flag that indicates if highlighting per tap (touch) is enabled
private var _highlightPerTapEnabled = true
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// Font object used for drawing the description text (by default in the bottom right corner of the chart)
public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0)
/// Text color used for drawing the description text
public var descriptionTextColor: UIColor? = UIColor.blackColor()
/// Text align used for drawing the description text
public var descriptionTextAlign: NSTextAlignment = NSTextAlignment.Right
/// Custom position for the description text in pixels on the screen.
public var descriptionTextPosition: CGPoint? = nil
/// font object for drawing the information text when there are no values in the chart
public var infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0)
public var infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the number of x-values the chart displays
internal var _deltaX = CGFloat(1.0)
/// the minimum x-value of the chart, regardless of zoom or translation.
internal var _chartXMin = Double(0.0)
/// the maximum x-value of the chart, regardless of zoom or translation.
internal var _chartXMax = Double(0.0)
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
public var highlighter: ChartHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
public var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
public var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
public var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
public var extraLeftOffset: CGFloat = 0.0
public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
_animator = ChartAnimator()
_animator.delegate = self
_viewPortHandler = ChartViewPortHandler()
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legend = ChartLegend()
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data
}
set
{
_offsetsCalculated = false
_data = newValue
// calculate how many digits are needed
if let data = _data
{
calculateFormatter(min: data.getYMin(), max: data.getYMax())
}
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil
_indicesToHighlight.removeAll()
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
_data?.clearValues()
setNeedsDisplay()
}
/// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
guard let data = _data else { return true }
if (data.yValCount <= 0)
{
return true
}
else
{
return false
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(min min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if let data = _data where data.xValCount >= 2
{
reference = fabs(max - min)
}
else
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
let digits = ChartUtils.decimals(reference)
_defaultValueFormatter.maximumFractionDigits = digits
_defaultValueFormatter.minimumFractionDigits = digits
}
public override func drawRect(rect: CGRect)
{
let optionalContext = UIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
let frame = self.bounds
if _data === nil
{
CGContextSaveGState(context)
defer { CGContextRestoreGState(context) }
let hasText = noDataText.characters.count > 0
let hasDescription = noDataTextDescription?.characters.count > 0
var textHeight = hasText ? infoFont.lineHeight : 0.0
if hasDescription
{
textHeight += infoFont.lineHeight
}
// if no data, inform the user
var y = (frame.height - textHeight) / 2.0
if hasText
{
ChartUtils.drawText(
context: context,
text: noDataText,
point: CGPoint(x: frame.width / 2.0, y: y),
align: .Center,
attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]
)
y = y + infoFont.lineHeight
}
if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0)
{
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: y), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
}
return
}
if (!_offsetsCalculated)
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(context context: CGContext)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return
}
let frame = self.bounds
var attrs = [String : AnyObject]()
var font = descriptionFont
if (font == nil)
{
#if os(tvOS)
// 23 is the smallest recommened font size on the TV
font = UIFont.systemFontOfSize(23, weight: UIFontWeightMedium)
#else
font = UIFont.systemFontOfSize(UIFont.systemFontSize())
#endif
}
attrs[NSFontAttributeName] = font
attrs[NSForegroundColorAttributeName] = descriptionTextColor
if descriptionTextPosition == nil
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: CGPoint(
x: frame.width - _viewPortHandler.offsetRight - 10.0,
y: frame.height - _viewPortHandler.offsetBottom - 10.0 - (font?.lineHeight ?? 0.0)),
align: descriptionTextAlign,
attributes: attrs)
}
else
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: descriptionTextPosition!,
align: descriptionTextAlign,
attributes: attrs)
}
}
// MARK: - Highlighting
/// - returns: the array of currently highlighted values. This might an empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// - default: true
public var highlightPerTapEnabled: Bool
{
get { return _highlightPerTapEnabled }
set { _highlightPerTapEnabled = newValue }
}
/// Returns true if values can be highlighted via tap gesture, false if not.
public var isHighLightPerTapEnabled: Bool
{
return highlightPerTapEnabled
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: true if there are values to highlight, false if there are no values to highlight.
public func valuesToHighlight() -> Bool
{
return _indicesToHighlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHighlight = highs ?? [ChartHighlight]()
if (_indicesToHighlight.isEmpty)
{
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = _indicesToHighlight[0];
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights the values represented by the provided Highlight object
/// This DOES NOT generate a callback to the delegate.
/// - parameter highlight: contains information about which entry should be highlighted
public func highlightValue(highlight: ChartHighlight?)
{
highlightValue(highlight: highlight, callDelegate: false)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
guard let data = _data else
{
print("Value not highlighted because data is nil")
return
}
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= data.xValCount || dataSetIndex >= data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate)
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if (h == nil)
{
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
// set the indices to highlight
entry = _data?.getEntryForHighlight(h!)
if (entry === nil || entry!.xIndex != h?.xIndex)
{
h = nil
entry = nil
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
_indicesToHighlight = [h!]
}
}
if (callDelegate && delegate != nil)
{
if (h == nil)
{
delegate!.chartValueNothingSelected?(self)
}
else
{
// notify the listener
delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!)
}
}
// redraw the chart
setNeedsDisplay()
}
/// The last value that was highlighted via touch.
public var lastHighlighted: ChartHighlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context context: CGContext)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return
}
for (var i = 0, count = _indicesToHighlight.count; i < count; i++)
{
let highlight = _indicesToHighlight[i]
let xIndex = highlight.xIndex
if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX))
{
let e = _data?.getEntryForHighlight(highlight)
if (e === nil || e!.xIndex != highlight.xIndex)
{
continue
}
let pos = getMarkerPosition(entry: e!, highlight: highlight)
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue
}
// callbacks to update the content
marker!.refreshContent(entry: e!, highlight: highlight)
let markerSize = marker!.size
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y))
}
else
{
marker!.draw(context: context, point: pos)
}
}
}
}
/// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase")
}
// MARK: - Animation
/// - returns: the animator responsible for animating chart values.
public var animator: ChartAnimator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: the current y-max value across all DataSets
public var chartYMax: Double
{
return _data?.yMax ?? 0.0
}
/// - returns: the current y-min value across all DataSets
public var chartYMin: Double
{
return _data?.yMin ?? 0.0
}
public var chartXMax: Double
{
return _chartXMax
}
public var chartXMin: Double
{
return _chartXMin
}
public var xValCount: Int
{
return _data?.xValCount ?? 0
}
/// - returns: the total number of (y) values the chart holds (across all DataSets)
public var valueCount: Int
{
return _data?.yValCount ?? 0
}
/// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: the center point of the chart (the whole View) in pixels.
public var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
public func setDescriptionTextPosition(x x: CGFloat, y: CGFloat)
{
descriptionTextPosition = CGPoint(x: x, y: y)
}
/// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend
}
/// - returns: the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer
}
/// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// - returns: the x-value at the given index
public func getXValue(index: Int) -> String!
{
guard let data = _data where data.xValCount > index else
{
return nil
}
return data.xVals[index]
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]()
guard let data = _data else { return vals }
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
let set = data.getDataSetByIndex(i)
let e = set.entryForXIndex(xIndex)
if (e !== nil)
{
vals.append(e!)
}
}
return vals
}
/// - returns: the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler
}
/// - returns: the bitmap that represents the chart.
public func getChartImage(transparent transparent: Bool) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor)
CGContextFillRect(context, rect)
}
}
if let context = context
{
layer.renderInContext(context)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case JPEG
case PNG
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter filePath: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
let image = getChartImage(transparent: format != .JPEG)
var imageData: NSData!
switch (format)
{
case .PNG:
imageData = UIImagePNGRepresentation(image)
break
case .JPEG:
imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
break
}
return imageData.writeToFile(path, atomically: true)
}
#if !os(tvOS)
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil)
}
#endif
internal typealias VoidClosureType = () -> ()
internal var _sizeChangeEventActions = [VoidClosureType]()
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// Finish any pending viewport changes
while (!_sizeChangeEventActions.isEmpty)
{
_sizeChangeEventActions.removeAtIndex(0)()
}
notifyDataSetChanged()
}
}
}
public func clearPendingViewPortChanges()
{
_sizeChangeEventActions.removeAll(keepCapacity: false)
}
/// **default**: true
/// - returns: true if chart continues to scroll after touch up, false if not.
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if (val < 0.0)
{
val = 0.0
}
if (val >= 1.0)
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay()
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesBegan(touches, withEvent: event)
}
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesMoved(touches, withEvent: event)
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesEnded(touches, withEvent: event)
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesCancelled(touches, withEvent: event)
}
}
}