forked from LoopKit/Loop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasalStateView.swift
More file actions
93 lines (70 loc) · 2.46 KB
/
BasalStateView.swift
File metadata and controls
93 lines (70 loc) · 2.46 KB
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
//
// BasalStateView.swift
// Naterade
//
// Created by Nathan Racklyeft on 5/12/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
public final class BasalStateView: UIView {
var netBasalPercent: Double = 0 {
didSet {
animateToPath(drawPath())
}
}
override public class var layerClass : AnyClass {
return CAShapeLayer.self
}
private var shapeLayer: CAShapeLayer {
return layer as! CAShapeLayer
}
override init(frame: CGRect) {
super.init(frame: frame)
shapeLayer.lineWidth = 2
updateTintColor()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
shapeLayer.lineWidth = 2
updateTintColor()
}
override public func layoutSubviews() {
super.layoutSubviews()
}
public override func tintColorDidChange() {
super.tintColorDidChange()
updateTintColor()
}
private func updateTintColor() {
shapeLayer.fillColor = tintColor.withAlphaComponent(0.5).cgColor
shapeLayer.strokeColor = tintColor.cgColor
}
private func drawPath() -> CGPath {
let startX = bounds.minX
let endX = bounds.maxX
let midY = bounds.midY
let path = UIBezierPath()
path.move(to: CGPoint(x: startX, y: midY))
let leftAnchor = startX + 1/6 * bounds.size.width
let rightAnchor = startX + 5/6 * bounds.size.width
let yAnchor = bounds.midY - CGFloat(netBasalPercent) * (bounds.size.height - shapeLayer.lineWidth) / 2
path.addLine(to: CGPoint(x: leftAnchor, y: midY))
path.addLine(to: CGPoint(x: leftAnchor, y: yAnchor))
path.addLine(to: CGPoint(x: rightAnchor, y: yAnchor))
path.addLine(to: CGPoint(x: rightAnchor, y: midY))
path.addLine(to: CGPoint(x: endX, y: midY))
return path.cgPath
}
private static let AnimationKey = "com.loudnate.Naterade.shapePathAnimation"
private func animateToPath(_ path: CGPath) {
if shapeLayer.path != nil {
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = shapeLayer.path ?? drawPath()
animation.toValue = path
animation.duration = 1
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
shapeLayer.add(animation, forKey: type(of: self).AnimationKey)
}
shapeLayer.path = path
}
}