Created By: Debasis Das (22-May-2017)
In this post we will create a simple animation of Column Chart value changes.
We will be using CABasicAnimation and CALayers for creating this effect.
// ViewController.swift // ColumnChart-RandomData-CoreAnimation // Created by Debasis Das on 5/15/17. // Copyright © 2017 Knowstack. All rights reserved. import Cocoa class ViewController: NSViewController { @IBOutlet weak var graphView:NSView! let noOfColumns = 30 override func viewDidLoad() { super.viewDidLoad() let layer = CALayer() layer.frame = self.graphView.frame layer.backgroundColor = NSColor.black.cgColor self.graphView.layer = layer self.graphView.wantsLayer = true let offset = 10 for i in 0...noOfColumns{ let columnLayer = CALayer() columnLayer.backgroundColor = NSColor.blue.cgColor columnLayer.frame = CGRect(x: offset+(i*20), y: 10, width: 10, height: 1) layer.addSublayer(columnLayer) } redrawGraph(self) } @IBAction func redrawGraph(_ sender: Any) { CATransaction.setAnimationDuration(2.0) for i in 0...noOfColumns{ let newHeight = CGFloat(arc4random()) / CGFloat(UInt32.max) * 200 + 40 var layerBounds = self.graphView.layer?.sublayers?[i].frame layerBounds?.size.height = newHeight self.graphView.layer?.sublayers?[i].frame = layerBounds! } } }
you can download the code hereColumnChart-RandomData-CoreAnimation
Leave a Reply