Hello!
I just started to explore the world of your amazing library. Thanks a lot for implementing.
I have a trouble with animation. Could you please help me with it?
I want to show live data with animation for every new point. Chart is blinkingbefore every animation. I've captured a video: https://www.youtube.com/watch?v=mQ5A78P8oXk
Code:
import UIKit
import SwiftyTimer
class NewChartViewController: UIViewController, TKChartDelegate {
@IBOutlet weak var chart: TKChart!
var timer: NSTimer!
var dataPoints = [TKChartDataPoint]()
override func viewDidLoad() {
super.viewDidLoad()
configureChart()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
configureTimer()
}
func chart(chart: TKChart, animationForSeries series: TKChartSeries, withState state: TKChartSeriesRenderState, inRect rect: CGRect) -> CAAnimation? {
var animations = [CAAnimation]()
if (state.points.count() <= 2) {
return nil
}
let indexOfLast = state.points.count() - 1
let indexOfLastButOne = state.points.count() - 2
let lastPoint = state.points[indexOfLast] as! TKChartVisualPoint
let lastButOnePoint = state.points[indexOfLastButOne] as! TKChartVisualPoint
let pointKeyPath = state.animationKeyPathForPointAtIndex(indexOfLast)!
let animationX = CABasicAnimation(keyPath: pointKeyPath + ".x")
animationX.fromValue = lastButOnePoint.x
animationX.toValue = lastPoint.x
animationX.duration = 0.4
animationX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animations.append(animationX)
let animationY = CABasicAnimation(keyPath: pointKeyPath + ".y")
animationY.fromValue = lastButOnePoint.y
animationY.toValue = lastPoint.y
animationY.duration = 0.4
animationY.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animations.append(animationY)
let group = CAAnimationGroup()
group.duration = 0.4
group.animations = animations
return group
}
private func configureTimer() {
timer = NSTimer.every(1.second) {
self.updateChart()
}
}
private func configureChart() {
chart.delegate = self
chart.allowAnimations = true
let periodAxis = TKChartDateTimeAxis()
chart.xAxis = periodAxis
}
private func updateChart () -> Void {
chart.removeAllData()
let dataPoint = TKChartDataPoint(x: NSDate(), y: Int(arc4random() % 70))
dataPoints.append(dataPoint)
chart.yAxis = TKChartNumericAxis(minimum: 0, andMaximum: 100)
let firstPoint = dataPoints[0]
let lastPoint = dataPoints[dataPoints.count - 1]
let xAxis = TKChartDateTimeAxis(minimumDate: firstPoint.dataXValue as! NSDate, andMaximumDate: (lastPoint.dataXValue as! NSDate).dateByAddingMinutes(1))
xAxis.style.labelStyle.fitMode = TKChartAxisLabelFitMode.None
xAxis.style.majorTickStyle.maxTickClippingMode = TKChartAxisClippingMode.Visible
xAxis.majorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Seconds
chart.xAxis = xAxis
chart.addSeries(TKChartLineSeries(items: dataPoints))
chart.reloadData()
}
}