Simple Pie Chart in Core Animation - ios

I'm trying to include a simple pie chart in my app using Core Animation.
I found an article on-line to copy and adjust, which seems to be close to what I need.
https://github.com/tomnoda/piechart_ios
The code refers to Nib files (which I don't really understand), but can I do this programmatically instead? I think this is the line of code that needs to change, and maybe I need to add some other coding as well:-
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let view: UIView = Bundle.main.loadNibNamed("PieChartView", owner: self, options: nil)!.first as! UIView
addSubview(view)
The let line refers to the Nib file, but how can I get it to refer to my View Controller instead?
This obviously results in a series of unresolved identifier errors, as the 2 files aren't linked as they should be. On the View Controller I have the following, as well as a number of other outlets:-
#IBOutlet weak var pieChartView: PieChartView!
As I'm new to Xcode hopefully there is a simple fix to this problem.

"I'm trying to include a simple pie chart in my app using Core Animation"
First, remove the word simple from that statement. Not to sound like a jerk, but if you are a beginner and don't even understand elements laid-out in a nib (xib) vs creating elements via code, you will have a long road ahead of you.
While the example you linked to "works," it has a lot of limitations and takes some rather odd approaches to the task. For example:
it is limited to 5 or fewer segments
the sum of the segment values must equal 1.0
it has very little in the way of error checking
That said, it could be a good place for you to start learning.
Here is the same code, modified to NOT need the xib file. It can be used like this:
class ViewController: UIViewController {
#IBOutlet var pieChartView: MyPieChartView!
override func viewDidLoad() {
super.viewDidLoad()
pieChartView.slices = [
Slice(percent: 0.4, color: UIColor.red),
Slice(percent: 0.3, color: UIColor.blue),
Slice(percent: 0.2, color: UIColor.purple),
Slice(percent: 0.1, color: UIColor.green)
]
}
override func viewDidAppear(_ animated: Bool) {
pieChartView.animateChart()
}
}
This is MyPieChartView.swift ...
First changes from the original PieChartView.swift file are at the top, between the:
// MARK: Changes start here
// MARK: Changes end here
Additional changes to allow "anti-clockwise" ... look for instances of new Bool var drawClockwise
import UIKit
class MyPieChartView: UIView {
static let ANIMATION_DURATION: CGFloat = 1.4
// MARK: Changes start here
var canvasView: UIView!
var label1: UILabel!
var label2: UILabel!
var label3: UILabel!
var label4: UILabel!
var label5: UILabel!
var label1XConst: NSLayoutConstraint!
var label2XConst: NSLayoutConstraint!
var label3XConst: NSLayoutConstraint!
var label4XConst: NSLayoutConstraint!
var label5XConst: NSLayoutConstraint!
var label1YConst: NSLayoutConstraint!
var label2YConst: NSLayoutConstraint!
var label3YConst: NSLayoutConstraint!
var label4YConst: NSLayoutConstraint!
var label5YConst: NSLayoutConstraint!
var drawClockwise: Bool = true
var slices: [Slice]?
var sliceIndex: Int = 0
var currentPercent: CGFloat = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
if canvasView == nil {
let container = UIView()
addSubview(container)
canvasView = UIView()
container.addSubview(canvasView)
canvasView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
canvasView.topAnchor.constraint(equalTo: container.topAnchor),
canvasView.leadingAnchor.constraint(equalTo: container.leadingAnchor),
canvasView.trailingAnchor.constraint(equalTo: container.trailingAnchor),
canvasView.bottomAnchor.constraint(equalTo: container.bottomAnchor),
])
canvasView.backgroundColor = .yellow
label1 = UILabel()
label2 = UILabel()
label3 = UILabel()
label4 = UILabel()
label5 = UILabel()
[label1, label2, label3, label4, label5].forEach {
guard let v = $0 else { fatalError("Bad Setup!") }
v.translatesAutoresizingMaskIntoConstraints = false
v.textColor = .white
v.textAlignment = .center
addSubview(v)
}
label1XConst = label1.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor)
label1YConst = label1.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor)
label2XConst = label2.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor)
label2YConst = label2.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor)
label3XConst = label3.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor)
label3YConst = label3.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor)
label4XConst = label4.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor)
label4YConst = label4.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor)
label5XConst = label5.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor)
label5YConst = label5.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor)
[label1XConst, label2XConst, label3XConst, label4XConst, label5XConst,
label1YConst, label2YConst, label3YConst, label4YConst, label5YConst].forEach {
$0?.isActive = true
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
subviews[0].frame = bounds
}
// don't do this
//override func draw(_ rect: CGRect) {
// subviews[0].frame = bounds
//}
// MARK: Changes end here
/// Get an animation duration for the passed slice.
/// If slice share is 40%, for example, it returns 40% of total animation duration.
///
/// - Parameter slice: Slice struct
/// - Returns: Animation duration
func getDuration(_ slice: Slice) -> CFTimeInterval {
return CFTimeInterval(slice.percent / 1.0 * PieChartView.ANIMATION_DURATION)
}
/// Convert slice percent to radian.
///
/// - Parameter percent: Slice percent (0.0 - 1.0).
/// - Returns: Radian
func percentToRadian(_ percent: CGFloat) -> CGFloat {
//Because angle starts wtih X positive axis, add 270 degrees to rotate it to Y positive axis.
var angle = 270 + percent * 360
if angle >= 360 {
angle -= 360
}
return angle * CGFloat.pi / 180.0
}
/// Add a slice CAShapeLayer to the canvas.
///
/// - Parameter slice: Slice to be drawn.
func addSlice(_ slice: Slice) {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = getDuration(slice)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.delegate = self
let canvasWidth = canvasView.frame.width
let toPercent = currentPercent + (drawClockwise ? slice.percent : -slice.percent)
let path = UIBezierPath(arcCenter: canvasView.center,
radius: canvasWidth * 3 / 8,
startAngle: percentToRadian(currentPercent),
endAngle: percentToRadian(toPercent),
clockwise: drawClockwise)
let sliceLayer = CAShapeLayer()
sliceLayer.path = path.cgPath
sliceLayer.fillColor = nil
sliceLayer.strokeColor = slice.color.cgColor
sliceLayer.lineWidth = canvasWidth * 2 / 8
sliceLayer.strokeEnd = 1
sliceLayer.add(animation, forKey: animation.keyPath)
canvasView.layer.addSublayer(sliceLayer)
}
/// Get label's center position based on from and to percentages.
/// This is always relative to canvasView's center.
///
/// - Parameters:
/// - fromPercent: End of previous slice.
/// - toPercent: End of current slice.
/// - Returns: Center point for label.
func getLabelCenter(_ fromPercent: CGFloat, _ toPercent: CGFloat) -> CGPoint {
let radius = canvasView.frame.width * 3 / 8
let labelAngle = percentToRadian((toPercent - fromPercent) / 2 + fromPercent)
let path = UIBezierPath(arcCenter: canvasView.center,
radius: radius,
startAngle: labelAngle,
endAngle: labelAngle,
clockwise: drawClockwise)
path.close()
return path.currentPoint
}
/// Re-position and draw label such as "43%".
///
/// - Parameter slice: Slice whose label is drawn.
func addLabel(_ slice: Slice) {
let center = canvasView.center
let labelCenter = getLabelCenter(currentPercent, currentPercent + (drawClockwise ? slice.percent : -slice.percent))
let xConst = [label1XConst, label2XConst, label3XConst, label4XConst, label5XConst][sliceIndex]
let yConst = [label1YConst, label2YConst, label3YConst, label4YConst, label5YConst][sliceIndex]
xConst?.constant = labelCenter.x - center.x
yConst?.constant = labelCenter.y - center.y
let label = [label1, label2, label3, label4, label5][sliceIndex]
label?.isHidden = true
label?.text = String(format: "%d%%", Int(slice.percent * 100))
}
/// Call this to start pie chart animation.
func animateChart() {
sliceIndex = 0
currentPercent = 0.0
canvasView.layer.sublayers = nil
if slices != nil && slices!.count > 0 {
let firstSlice = slices![0]
addLabel(firstSlice)
addSlice(firstSlice)
}
}
}
extension MyPieChartView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
currentPercent += (drawClockwise ? slices![sliceIndex].percent : -slices![sliceIndex].percent)
sliceIndex += 1
if sliceIndex < slices!.count {
let nextSlice = slices![sliceIndex]
addLabel(nextSlice)
addSlice(nextSlice)
} else {
//After animation is done, display all labels. Can be animated.
for label in [label1, label2, label3, label4, label5] {
label?.isHidden = false
}
}
}
}
}
Example:
class ViewController: UIViewController {
#IBOutlet var pieChartView: MyPieChartView!
#IBOutlet var antiPieChartView: MyPieChartView!
override func viewDidLoad() {
super.viewDidLoad()
pieChartView.slices = [
Slice(percent: 0.4, color: UIColor.red),
Slice(percent: 0.3, color: UIColor.blue),
Slice(percent: 0.2, color: UIColor.purple),
Slice(percent: 0.1, color: UIColor(red: 0.0, green: 0.75, blue: 0.0, alpha: 1.0))
]
antiPieChartView.slices = [
Slice(percent: 0.4, color: UIColor.red),
Slice(percent: 0.3, color: UIColor.blue),
Slice(percent: 0.2, color: UIColor.purple),
Slice(percent: 0.1, color: UIColor(red: 0.0, green: 0.75, blue: 0.0, alpha: 1.0))
]
// draw this pie anti-clockwise
antiPieChartView.drawClockwise = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pieChartView.animateChart()
antiPieChartView.animateChart()
}
}

Related

Initializing an instance from Custom ProgressBar Class into UItableviewCell

I'm trying to create a circular progressBar with timer function in my UItableviewCell class. I have created a custom class timer, and I am using Jonni's progressBar template (Credit to
Jonni Åkesson) from - https://github.com/innoj/CountdownTimer.
The only noticeable difference between my code and source template is that I am adding the Custom ProgressBar class UIView programmatically whereas the source template used IBOutlet to connect to the Custom ProgressBar Class.
My goal is to ensure that the CAShapeLayers (both actual and background layers are shown as per below image - Source: https://www.youtube.com/watch?v=-KwFvGVstyc
Below is my code and I am unable to see both front CAShapeLayer and background CAShapeLayer. I am suspecting a logical error when I initialize constant "progressBar".
Please advise if it is possible to utilize the Custom ProgressBar Class, instead of re-writing the entire code.
import Foundation
import UIKit
import IQKeyboardManagerSwift
class ActiveExerciseTableViewCell: UITableViewCell, UITextFieldDelegate {
let progressBar: ProgressBar = {
let progressBar = ProgressBar()
return progressBar
}()
lazy var activeExerciseTimerUIView: UIView = { [weak self] in
let activeExerciseTimerUIView = UIView()
activeExerciseTimerUIView.backgroundColor = .black
activeExerciseTimerUIView.isUserInteractionEnabled = true
activeExerciseTimerUIView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTimerView)))
return activeExerciseTimerUIView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(activeExerciseTimerUIView)
}
override func layoutSubviews() {
super.layoutSubviews()
setUpActiveExerciseUIViewLayout()
}
func setUpActiveExerciseUIViewLayout(){
activeExerciseTimerUIView.translatesAutoresizingMaskIntoConstraints = false
activeExerciseTimerUIView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
activeExerciseTimerUIView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: (contentView.frame.height-tableviewContentViewTabBarHeight)*0.25).isActive = true
activeExerciseTimerUIView.widthAnchor.constraint(equalToConstant: 225).isActive = true
activeExerciseTimerUIView.heightAnchor.constraint(equalToConstant: 225).isActive = true
activeExerciseTimerUIView.layer.cornerRadius = activeExerciseTimerUIView.frame.width/2
progressBar.frame = CGRect(
x: 0,
y: 0,
width: activeExerciseTimerUIView.frame.width,
height: activeExerciseTimerUIView.frame.height)
self.activeExerciseTimerUIView.addSubview(progressBar)
}
Below is the Custom ProgressBar Class from source file.
import UIKit
class ProgressBar: UIView, CAAnimationDelegate {
fileprivate var animation = CABasicAnimation()
fileprivate var animationDidStart = false
fileprivate var timerDuration = 0
lazy var fgProgressLayer: CAShapeLayer = {
let fgProgressLayer = CAShapeLayer()
return fgProgressLayer
}()
lazy var bgProgressLayer: CAShapeLayer = {
let bgProgressLayer = CAShapeLayer()
return bgProgressLayer
}()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
loadBgProgressBar()
loadFgProgressBar()
}
override init(frame: CGRect) {
super.init(frame: frame)
loadBgProgressBar()
loadFgProgressBar()
}
fileprivate func loadFgProgressBar() {
let startAngle = CGFloat(-Double.pi / 2)
let endAngle = CGFloat(3 * Double.pi / 2)
let centerPoint = CGPoint(x: frame.width/2 , y: frame.height/2)
let gradientMaskLayer = gradientMask()
fgProgressLayer.path = UIBezierPath(arcCenter:centerPoint, radius: frame.width/2 - 30.0, startAngle:startAngle, endAngle:endAngle, clockwise: true).cgPath
fgProgressLayer.backgroundColor = UIColor.clear.cgColor
fgProgressLayer.fillColor = nil
fgProgressLayer.strokeColor = UIColor.black.cgColor
fgProgressLayer.lineWidth = 4.0
fgProgressLayer.strokeStart = 0.0
fgProgressLayer.strokeEnd = 0.0
gradientMaskLayer.mask = fgProgressLayer
layer.addSublayer(gradientMaskLayer)
}
fileprivate func gradientMask() -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.locations = [0.0, 1.0]
let colorTop: AnyObject = CustomColor.lime.cgColor
let colorBottom: AnyObject = CustomColor.lime.cgColor
let arrayOfColors: [AnyObject] = [colorTop, colorBottom]
gradientLayer.colors = arrayOfColors
return gradientLayer
}
fileprivate func loadBgProgressBar() {
let startAngle = CGFloat(-Double.pi / 2)
let endAngle = CGFloat(3 * Double.pi / 2)
let centerPoint = CGPoint(x: frame.width/2 , y: frame.height/2)
let gradientMaskLayer = gradientMaskBg()
bgProgressLayer.path = UIBezierPath(arcCenter:centerPoint, radius: frame.width/2 - 30.0, startAngle:startAngle, endAngle:endAngle, clockwise: true).cgPath
bgProgressLayer.backgroundColor = UIColor.clear.cgColor
bgProgressLayer.fillColor = nil
bgProgressLayer.strokeColor = UIColor.black.cgColor
bgProgressLayer.lineWidth = 4.0
bgProgressLayer.strokeStart = 0.0
bgProgressLayer.strokeEnd = 1.0
gradientMaskLayer.mask = bgProgressLayer
layer.addSublayer(gradientMaskLayer)
}
fileprivate func gradientMaskBg() -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.locations = [0.0, 1.0]
let colorTop: AnyObject = CustomColor.strawberry.cgColor
let colorBottom: AnyObject = CustomColor.strawberry.cgColor
let arrayOfColors: [AnyObject] = [colorTop, colorBottom]
gradientLayer.colors = arrayOfColors
return gradientLayer
}
Resolve the issue by loading the background and foreground progress bars in layoutSubViews function.
ProgressBar.swift
import UIKit
import Pulsator
class ProgressBar: UIView, CAAnimationDelegate {
fileprivate var animation = CABasicAnimation()
fileprivate var animationDidStart = false
fileprivate var updatedAnimationAdded = false
fileprivate var updateExecuted = false
fileprivate var totalTimerDuration = 0
fileprivate var isProgressBarAdded:Bool = false
fileprivate var barlineWidth: CGFloat = 8
// let pulsator = Pulsator()
// fileprivate var width: CGFloat
// fileprivate var height: CGFloat
//
lazy var fgProgressLayer: CAShapeLayer = {
let fgProgressLayer = CAShapeLayer()
return fgProgressLayer
}()
lazy var bgProgressLayer: CAShapeLayer = {
let bgProgressLayer = CAShapeLayer()
return bgProgressLayer
}()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
loadBgProgressBar()
loadFgProgressBar()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
super.layoutSubviews()
if self.frame.width > 0 && self.frame.height > 0 && isProgressBarAdded == false {
loadBgProgressBar()
loadFgProgressBar()
isProgressBarAdded = true
}
}

Recall drawRect after view is recalled

I have a view that is using drawRect to draw a round timer.
In its superview there's a button that pushes another VC to the screen.
The problem is when the user clicks the back button, the timer (which is drawn using drawRect) is automatically starting with the toValue value instad of the fromValue. I want it to be redrawed exactly as it is drawn when I first launch the view.
Does anybody know how can I achieve that?
Thank you!
Code:
class CountDownTimer: UIView {
public var backgroundStrokeColor: CGColor = UIColor.white.cgColor
public var backgroundFillColor: CGColor = UIColor.clear.cgColor
public var backgroundLineWidth: CGFloat = 15
public var timeLeftSrtokeColor: CGColor = UIColor.red.cgColor
public var timeLeftFillColor: CGColor = UIColor.clear.cgColor
public var timeLeftLineWidth: CGFloat = 10
public var textColor: UIColor = UIColor.white
public var textFont: UIFont = UIFont.balooRegular(10.0)
fileprivate var timeLeft: TimeInterval = 0
fileprivate var endDate: Date?
fileprivate var timeLeftShapeLayer: CAShapeLayer?
fileprivate var bgShapeLayer: CAShapeLayer?
fileprivate var timeLabel: UILabel?
fileprivate var timer = Timer()
fileprivate let strokeIt = CABasicAnimation(keyPath: "strokeEnd")
//MARK: - UIView
override func draw(_ rect: CGRect) {
drawBgShape()
drawTimeLeftShape()
addTimeLabel()
strokeIt.toValue = 1 //"fromValue" is set in "startTimer(duration, timerProgress)
strokeIt.duration = self.timeLeft
// add the animation to your timeLeftShapeLayer
timeLeftShapeLayer?.add(strokeIt, forKey: nil)
// define the future end time by adding the timeLeft to now Date()
}
//MARK: - Public
public func startTimer(duration: TimeInterval, timerProgress: Double) {
self.timeLeft = duration
endDate = Date().addingTimeInterval(timeLeft)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
strokeIt.fromValue = timerProgress
}
//MARK: - Private
fileprivate func drawBgShape() {
//we initialize and add the layer only if there is not initialized
if(bgShapeLayer == nil){
bgShapeLayer = CAShapeLayer()
self.layer.addSublayer(bgShapeLayer!)
}
bgShapeLayer?.path = UIBezierPath(arcCenter: CGPoint(x: self.frame.midX , y: self.frame.midY), radius:
min((frame.width - self.timeLeftLineWidth)/2, (frame.height - self.timeLeftLineWidth)/2), startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true).cgPath
bgShapeLayer?.strokeColor = self.backgroundStrokeColor
bgShapeLayer?.fillColor = self.backgroundFillColor
bgShapeLayer?.lineWidth = self.backgroundLineWidth
}
fileprivate func drawTimeLeftShape() {
//we initialize and add the layer only if there is not initialized
if(timeLeftShapeLayer == nil){
timeLeftShapeLayer = CAShapeLayer()
self.layer.addSublayer(timeLeftShapeLayer!)
}
timeLeftShapeLayer?.path = UIBezierPath(arcCenter: CGPoint(x: self.frame.midX , y: self.frame.midY), radius:
min((frame.width - self.timeLeftLineWidth)/2, (frame.height - self.timeLeftLineWidth)/2), startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true).cgPath
timeLeftShapeLayer?.strokeColor = self.timeLeftSrtokeColor
timeLeftShapeLayer?.fillColor = self.timeLeftFillColor
timeLeftShapeLayer?.lineWidth = self.timeLeftLineWidth
}
fileprivate func addTimeLabel() {
//we initialize and add the UILabel only if there is not initialized
if(timeLabel == nil){
timeLabel = UILabel()
self.addSubview(timeLabel!)
}
timeLabel?.frame = CGRect(x: self.frame.midX-50 ,y: self.frame.midY-25, width: 100, height: 50)
timeLabel?.adjustsFontSizeToFitWidth = true
timeLabel?.textAlignment = .center
timeLabel?.text = self.timeLeft.stringTime
timeLabel?.textColor = self.textColor
timeLabel?.font = self.textFont
}
//MARK: - Actions
#objc fileprivate func updateTime() {
if timeLeft > 0 {
timeLeft = endDate?.timeIntervalSinceNow ?? 0
timeLabel?.text = self.timeLeft.stringTime
} else {
timeLabel?.text = self.timeLeft.stringTime
timer.invalidate()
}
}
}

Force custom view to redraw (or invalidate) using a timer

I've created a custom widget, which is animated. Now my problem is that I can't redraw the view, when the corresponding data gets updated.
Just don't hold anything against me in the code. This is my first piece of code in swift and I haven't worked with neither swift nor with Objective-C :-D
And also I've read the following questions, but they didn't help me:
How to force a view to render itself?
what-is-the-most-robust-way-to-force-a-uiview-to-redraw
p.s. : I can see the output of print(digit.phase) in the console.
p.s.s: I've also used performSelectorOnMainThread for calling the setNeedsDisplay function
The code:
import UIKit
struct Digit {
var targetDigit: Int
var currentDigit: Int
var phase: Float
}
#IBDesignable class RollerCounter: UIView {
var view: UIView!
var viewRect: CGRect!
var intNumber: Int
var digits = [Digit]()
let baseY = 20
var timer: NSTimer?
#IBInspectable var number: Int {
get {
return intNumber
}
set(number) {
intNumber = number
digits = []
var tempNumber:Int = intNumber
while tempNumber > 0 {
digits.append(Digit(targetDigit: tempNumber % 10, currentDigit: Int(rand()) % 10, phase: 0.0))
tempNumber /= 10
}
}
}
//init
override init(frame: CGRect) {
// set properties:
intNumber = 1111
super.init(frame: frame)
// setup the thing!
setup()
}
required init?(coder aDecoder: NSCoder) {
intNumber = 1111
super.init(coder: aDecoder)
// setup the thing
setup()
}
// Inital setup
func setup() {
let viewRect = CGRect(x: 0, y: 0, width: 280, height: 40)
view = UIView(frame: viewRect)
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
self.setNeedsDisplay()
backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.0)
}
func animate() {
timer = NSTimer.scheduledTimerWithTimeInterval(0.016, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
}
func tick() {
for var digit in digits {
digit.phase += Float(rand() % 100) / 100
print(digit.phase)
}
setNeedsDisplay()
//TEST: Also tested this
// if let rect = viewRect {
// drawRect(rect)
// } else {
// viewRect = CGRect(x: 0, y: 0, width: 280, height: 40)
// drawRect(viewRect
// }
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
var tempNumber: Int = number
let strTempNumber = String(tempNumber)
var index: Int = 1
let width = Float(rect.width)
let charWidth: Float = Float(rect.width) / Float(strTempNumber.characters.count)
let charHeight: CGFloat = 36
let color = UIColor.blackColor()
let font: UIFont = UIFont(name: "Helvetica Neue", size: charHeight)!
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = 6.0
let skew = 0.1
let textAttribs = [
NSForegroundColorAttributeName: color,
NSParagraphStyleAttributeName: paraStyle,
NSObliquenessAttributeName: skew,
NSFontAttributeName: font
]
for digit in digits {
let strCurrentDigit: NSString = String(digit.currentDigit) as NSString
let strNextDigit: NSString = String(digit.currentDigit - 1) as NSString
let xPos = width - Float(index) * charWidth
let yPos = Float(baseY) + Float(charHeight) * digit.phase
let point: CGPoint = CGPoint(x: Int(xPos), y: Int(yPos))
strCurrentDigit.drawAtPoint(point, withAttributes: textAttribs)
let nextDigitYPos = yPos - Float(charHeight) * 1.2
let nextDigitPoint: CGPoint = CGPoint(x: Int(xPos), y: Int(nextDigitYPos))
strNextDigit.drawAtPoint(nextDigitPoint, withAttributes: textAttribs)
index++
tempNumber /= 10
}
}
}
Sorry folks. My bad :-(
There's nothing wrong with the invalidation system. Here's what's wrong:
for var digit in digits {
digit.phase += Float(rand() % 100) / 100
print(digit.phase)
}
As it turns out, the changes to phase only get reflected in the local digit instance inside the for loop
But just to be clear, the setNeedsDisplay() call inside the tick method is crucial for the view to be updated.

Pie Chart slices in swift

I'm trying to make a pie chart. Actually it's done, but I would like to get some values, and each value should be a slice of the pie. The only thing I could do is fill the pie with a slider. How can I make different slices with different colors for some values?
Here is my code for drawing the chart (I got here in stack) :
import UIKit
#IBDesignable class ChartView: UIView {
#IBInspectable var progress : Double = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
#IBInspectable var noProgress : Double = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.contentMode = .Redraw
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.contentMode = .Redraw
}
override func drawRect(rect: CGRect) {
let color = UIColor.blueColor().CGColor
let lineWidth : CGFloat = 2.0
// Calculate box with insets
let margin: CGFloat = lineWidth
let box0 = CGRectInset(self.bounds, margin, margin)
let side : CGFloat = min(box0.width, box0.height)
let box = CGRectMake((self.bounds.width-side)/2, (self.bounds.height-side)/2,side,side)
let ctx = UIGraphicsGetCurrentContext()
// Draw outline
CGContextBeginPath(ctx)
CGContextSetStrokeColorWithColor(ctx, UIColor.blackColor().CGColor)
CGContextSetLineWidth(ctx, lineWidth)
CGContextAddEllipseInRect(ctx, box)
CGContextClosePath(ctx)
CGContextStrokePath(ctx)
// Draw arc
let delta : CGFloat = -CGFloat(M_PI_2)
let radius : CGFloat = min(box.width, box.height)/2.0
func prog_to_rad(p: Double) -> CGFloat {
let rad = CGFloat((p * M_PI)/180)
return rad
}
func draw_arc(s: CGFloat, e: CGFloat, color: CGColor) {
CGContextBeginPath(ctx)
CGContextMoveToPoint(ctx, box.midX, box.midY)
CGContextSetFillColorWithColor(ctx, color)
CGContextAddArc(ctx, box.midX, box.midY, radius-lineWidth/2, s, e, 0)
CGContextClosePath(ctx)
CGContextFillPath(ctx)
}
if progress > 0 {
let s = prog_to_rad(noProgress * 360/100)
let e = prog_to_rad(progress * 360/100)
draw_arc(s, e, color)
}
}
}
And here is my ViewController:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var pieChartView: ChartView!
#IBOutlet weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func setValue(sender: UISlider) {
pieChartView.progress = Double(sender.value)
}
}
This code is from my blogpost, it uses CAShapeLayer and UIBezierPath. You can create any number of segments with whichever choice of colour you like.
extension CGFloat {
func radians() -> CGFloat {
let b = CGFloat(M_PI) * (self/180)
return b
}
}
extension UIBezierPath {
convenience init(circleSegmentCenter center:CGPoint, radius:CGFloat, startAngle:CGFloat, endAngle:CGFloat)
{
self.init()
self.moveToPoint(CGPointMake(center.x, center.y))
self.addArcWithCenter(center, radius:radius, startAngle:startAngle.radians(), endAngle: endAngle.radians(), clockwise:true)
self.closePath()
}
}
func pieChart(pieces:[(UIBezierPath, UIColor)], viewRect:CGRect) -> UIView {
var layers = [CAShapeLayer]()
for p in pieces {
let layer = CAShapeLayer()
layer.path = p.0.CGPath
layer.fillColor = p.1.CGColor
layer.strokeColor = UIColor.whiteColor().CGColor
layers.append(layer)
}
let view = UIView(frame: viewRect)
for l in layers {
view.layer.addSublayer(l)
}
return view
}
let rectSize = CGRectMake(0,0,400,400)
let centrePointOfChart = CGPointMake(CGRectGetMidX(rectSize),CGRectGetMidY(rectSize))
let radius:CGFloat = 100
let piePieces = [(UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 250, endAngle: 360),UIColor.brownColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 0, endAngle: 200),UIColor.orangeColor()), (UIBezierPath(circleSegmentCenter: centrePointOfChart, radius: radius, startAngle: 200, endAngle: 250),UIColor.lightGrayColor())]
pieChart(piePieces, viewRect: CGRectMake(0,0,400,400))
You posted a bunch of code that appears to draw a single pie chart "slice" in a single color.
Are you saying that you don't know how to make it draw an entire pie, with slices of different sizes, and that you don't know how to make each slice a different color?
It sounds to me like you are copy/pasting code you got from somewhere and have no idea how it works. How about you walk us through what your code does and give us a clearer idea of where you're stuck?
We're not here to take your copy/paste code and modify it for you to make it meet your requirements. Sounds like custom development to me. I don't know about the other posters on this board, but I get paid for that.
As it happens I've written a development blog post that includes a sample app that generates pie charts in Swift. You can see it here:
http://wareto.com/swift-piecharts
Instead of overriding drawRect like the code you posted, it creates a CAShapeLayer that holds the pie chart. It manages a pie chart with a variable number of "slices", and will either change the arc of each slice, the radius, or both.
It is not set up to make each slice a different color. For that you'd have to modify it to use separate shape layers for each slice, which would be a fairly big structural change to the program.
It does at least show you how to draw a pie chart in Swift for iOS:
Below Code is useful for Pie Chart Slice space in swift. Check out once
import UIKit
private extension CGFloat {
/// Formats the CGFloat to a maximum of 1 decimal place.
var formattedToOneDecimalPlace : String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 1
return formatter.string(from: NSNumber(value: self.native)) ?? "\(self)"
}
}
/// Defines a segment of the pie chart
struct Segment {
/// The color of the segment
var color : UIColor
/// The name of the segment
var name : String
/// The value of the segment
var value : CGFloat
}
class PieChartView: UIView {
/// An array of structs representing the segments of the pie chart
var segments = [Segment]() {
didSet {
totalValue = segments.reduce(0) { $0 + $1.value }
setupLabels()
setNeedsDisplay() // re-draw view when the values get set
layoutLabels();
} // re-draw view when the values get set
}
/// Defines whether the segment labels should be shown when drawing the pie chart
var showSegmentLabels = true {
didSet { setNeedsDisplay() }
}
/// Defines whether the segment labels will show the value of the segment in brackets
var showSegmentValueInLabel = false {
didSet { setNeedsDisplay() }
}
/// The font to be used on the segment labels
var segmentLabelFont = UIFont.systemFont(ofSize: 14) {
didSet {
textAttributes[NSAttributedStringKey.font] = segmentLabelFont
setNeedsDisplay()
}
}
private let paragraphStyle : NSParagraphStyle = {
var p = NSMutableParagraphStyle()
p.alignment = .center
return p.copy() as! NSParagraphStyle
}()
private lazy var textAttributes : [NSAttributedStringKey : NSObject] = {
return [NSAttributedStringKey.paragraphStyle : self.paragraphStyle, NSAttributedStringKey.font : self.segmentLabelFont]
}()
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = false // when overriding drawRect, you must specify this to maintain transparency.
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private var labels: [UILabel] = []
private var totalValue: CGFloat = 1;
override func draw(_ rect: CGRect) {
let anglePI2 = (CGFloat.pi * 2)
let center = CGPoint.init(x: bounds.size.width / 2, y: bounds.size.height / 2)
let radius = min(bounds.size.width, bounds.size.height) / 2;
let lineWidth: CGFloat = 1.5;
let ctx = UIGraphicsGetCurrentContext()
ctx?.setLineWidth(lineWidth)
var currentAngle: CGFloat = 0
if totalValue <= 0 {
totalValue = 1
}
let iRange = 0 ..< segments.count
for i in iRange {
let segment = segments[i]
// calculate percent
let percent = segment.value / totalValue
let angle = anglePI2 * percent
ctx?.beginPath()
ctx?.move(to: center)
ctx?.addArc(center: center, radius: radius - lineWidth, startAngle: currentAngle, endAngle: currentAngle + angle, clockwise: false)
ctx?.closePath()
ctx?.setFillColor(segment.color.cgColor)
ctx?.fillPath()
ctx?.beginPath()
ctx?.move(to: center)
ctx?.addArc(center: center, radius: radius - (lineWidth / 2), startAngle: currentAngle, endAngle: currentAngle + angle, clockwise: false)
ctx?.closePath()
ctx?.setStrokeColor(UIColor.white.cgColor)
ctx?.strokePath()
currentAngle += angle
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.layoutLabels()
}
private func setupLabels() {
var diff = segments.count - labels.count;
if diff >= 0 {
for _ in 0 ..< diff {
let lbl = UILabel()
self.addSubview(lbl)
labels.append(lbl)
}
} else {
while diff != 0 {
var lbl: UILabel!
if labels.count <= 0 {
break;
}
lbl = labels.removeLast()
if lbl.superview != nil {
lbl.removeFromSuperview()
}
diff += 1;
}
}
for i in 0 ..< segments.count {
let lbl = labels[i]
lbl.textColor = UIColor.white
// Change here for your text display
// I currently display percent of each pies
lbl.text = "\(segments[i].value.formattedToOneDecimalPlace)%" //String.init(format: "%0.0f", segments[i].value)
lbl.font = UIFont.systemFont(ofSize: 14)
}
}
func layoutLabels() {
let anglePI2 = CGFloat.pi * 2
let center = CGPoint.init(x: bounds.size.width / 2, y: bounds.size.height / 2)
let radius = min(bounds.size.width / 2, bounds.size.height / 2) / 1.5
var currentAngle: CGFloat = 0;
let iRange = 0 ..< labels.count
for i in iRange {
let lbl = labels[i]
let percent = segments[i].value / totalValue
let intervalAngle = anglePI2 * percent;
lbl.frame = .zero;
lbl.sizeToFit()
let x = center.x + radius * cos(currentAngle + (intervalAngle / 2))
let y = center.y + radius * sin(currentAngle + (intervalAngle / 2))
lbl.center = CGPoint.init(x: x, y: y)
currentAngle += intervalAngle
}
}
}

Changing bounds of a child view centers it in its parent

I have been following a tutorial explaining a custom ios control. There is no problem with the tutorial but I got really confused about the frame/bounds clipping (not part of the tutorial).
I have a UIView instance in the scene in the storyboard. This UIView is sized at 120 x 120. I am adding a custom control (extending UIControl) to this container view with addSubview. I began to experiment with setting different widths and height to the frame and bounds of the custom control, this is the initializer of the control:
public override init(frame: CGRect) {
super.init(frame: frame)
createSublayers()
}
...and produces this result (red is the parent, blue circle is the child):
Now I change the init to this:
public override init(frame: CGRect) {
super.init(frame: frame)
createSublayers()
self.frame.size.width = 40
self.frame.size.height = 40
println("frame: \(self.frame)")
println("bounds: \(self.bounds)")
self.clipsToBounds = true
}
And that produces this result:
and prints:
frame: (0.0,0.0,40.0,40.0)
bounds: (0.0,0.0,40.0,40.0)
But when I change the initliazer to this:
public override init(frame: CGRect) {
super.init(frame: frame)
createSublayers()
self.bounds.size.width = 40
self.bounds.size.height = 40
println("frame: \(self.frame)")
println("bounds: \(self.bounds)")
self.clipsToBounds = true
}
I get this:
and prints: frame: (40.0,40.0,40.0,40.0)
bounds: (0.0,0.0,40.0,40.0)
I cannot seem to comprehend why this view is centered in its parent view when I change its bounds. What exactly is causing it? Is the 'frame' clipped always towards its center? Or is this view centered in its parent after the bounds have been modified and that causes the update of the 'frame'? Is it some property that can be changed? How could I manage to put it to top-left corner, for example (exactly in the same way as when I modify the 'frame')? Thanks a lot!
EDIT:
class ViewController: UIViewController {
#IBOutlet var knobPlaceholder: UIView!
#IBOutlet var valueLabel: UILabel!
#IBOutlet var valueSlider: UISlider!
#IBOutlet var animateSwitch: UISwitch!
var knob: Knob!
override func viewDidLoad() {
super.viewDidLoad()
knob = Knob(frame: knobPlaceholder.bounds)
knobPlaceholder.addSubview(knob)
knobPlaceholder.backgroundColor = UIColor.redColor();
}
#IBAction func sliderValueChanged(slider: UISlider) {
}
#IBAction func randomButtonTouched(button: UIButton) {
}
}
And the knob:
public class Knob: UIControl {
private let knobRenderer = KnobRenderer()
private var backingValue: Float = 0.0
/** Contains the receiver’s current value. */
public var value: Float {
get {
return backingValue
}
set {
setValue(newValue, animated: false)
}
}
/** Sets the receiver’s current value, allowing you to animate the change visually. */
public func setValue(value: Float, animated: Bool) {
if value != backingValue {
backingValue = min(maximumValue, max(minimumValue, value))
}
}
/** Contains the minimum value of the receiver. */
public var minimumValue: Float = 0.0
/** Contains the maximum value of the receiver. */
public var maximumValue: Float = 1.0
public override init(frame: CGRect) {
super.init(frame: frame)
createSublayers()
self.bounds.size.width = 40
self.bounds.size.height = 40
println("frame: \(self.frame)")
println("bounds: \(self.bounds)")
self.clipsToBounds = true
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createSublayers() {
knobRenderer.update(bounds)
knobRenderer.strokeColor = tintColor
knobRenderer.startAngle = -CGFloat(M_PI * 11.0 / 8.0);
knobRenderer.endAngle = CGFloat(M_PI * 3.0 / 8.0);
knobRenderer.pointerAngle = knobRenderer.startAngle;
knobRenderer.lineWidth = 2.0
knobRenderer.pointerLength = 6.0
layer.addSublayer(knobRenderer.trackLayer)
layer.addSublayer(knobRenderer.pointerLayer)
}
}
private class KnobRenderer {
let trackLayer = CAShapeLayer()
let pointerLayer = CAShapeLayer()
var strokeColor: UIColor {
get {
return UIColor(CGColor: trackLayer.strokeColor)
}
set(strokeColor) {
trackLayer.strokeColor = strokeColor.CGColor
pointerLayer.strokeColor = strokeColor.CGColor
}
}
var lineWidth: CGFloat = 1.0 {
didSet {
update();
}
}
var startAngle: CGFloat = 0.0 {
didSet {
update();
}
}
var endAngle: CGFloat = 0.0 {
didSet {
update()
}
}
var backingPointerAngle: CGFloat = 0.0
var pointerAngle: CGFloat {
get { return backingPointerAngle }
set { setPointerAngle(newValue, animated: false) }
}
func setPointerAngle(pointerAngle: CGFloat, animated: Bool) {
backingPointerAngle = pointerAngle
}
var pointerLength: CGFloat = 0.0 {
didSet {
update()
}
}
init() {
trackLayer.fillColor = UIColor.clearColor().CGColor
pointerLayer.fillColor = UIColor.clearColor().CGColor
}
func updateTrackLayerPath() {
let arcCenter = CGPoint(x: trackLayer.bounds.width / 2.0, y: trackLayer.bounds.height / 2.0)
let offset = max(pointerLength, trackLayer.lineWidth / 2.0)
let radius = min(trackLayer.bounds.height, trackLayer.bounds.width) / 2.0 - offset;
trackLayer.path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true).CGPath
}
func updatePointerLayerPath() {
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: pointerLayer.bounds.width - pointerLength - pointerLayer.lineWidth / 2.0, y: pointerLayer.bounds.height / 2.0))
path.addLineToPoint(CGPoint(x: pointerLayer.bounds.width, y: pointerLayer.bounds.height / 2.0))
pointerLayer.path = path.CGPath
}
func update(bounds: CGRect) {
let position = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
trackLayer.bounds = bounds
trackLayer.position = position
pointerLayer.bounds = bounds
pointerLayer.position = position
update()
}
func update() {
trackLayer.lineWidth = lineWidth
pointerLayer.lineWidth = lineWidth
updateTrackLayerPath()
updatePointerLayerPath()
}
}
In your update function you are centering the view.
func update(bounds: CGRect) {
**let position = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)**
trackLayer.bounds = bounds
trackLayer.position = position
pointerLayer.bounds = bounds
pointerLayer.position = position
update()
}
If you take that out, then you're view won't be centered anymore. The reason setting the frame would leave it in the upper left hand corner while setting the bounds resulted in it being in the center is because setting the bounds x/y does not override the frame x/y. When you set the frame then later on your code only sets the bounds, so the frame x/y is never overwritten so the view stays in the upper left hand corner. However, in the second there is no x/y set for the frame, so I guess it's taken what you set for the bounds, so it get's centered.
I would recommend not setting the bounds x/y for the view as that should always be 0, 0. If you want to reposition it then use the frame. Remember the frame is relative the parent while the bounds is relative to it's self.

Resources