On UIView you can change the backgroundColour animated. And on a UISlideView you can change the value animated.
Can you add a custom property to your own UIView subclass so that it can be animated?
If I have a CGPath within my UIView then I can animate the drawing of it by changing the percentage drawn of the path.
Can I encapsulate that animation into the subclass.
i.e. I have a UIView with a CGPath that creates a circle.
If the circle is not there it represents 0%. If the circle is full it represents 100%. I can draw any value by changing the percentage drawn of the path. I can also animate the change (within the UIView subclass) by animating the percentage of the CGPath and redrawing the path.
Can I set some property (i.e. percentage) on the UIView so that I can stick the change into a UIView animateWithDuration block and it animate the change of the percentage of the path?
I hope I have explained what I would like to do well.
Essentially, all I want to do is something like...
[UIView animateWithDuration:1.0
animations:^{
myCircleView.percentage = 0.7;
}
completion:nil];
and the circle path animate to the given percentage.
If you extend CALayer and implement your custom
- (void) drawInContext:(CGContextRef) context
You can make an animatable property by overriding needsDisplayForKey (in your custom CALayer class) like this:
+ (BOOL) needsDisplayForKey:(NSString *) key {
if ([key isEqualToString:#"percentage"]) {
return YES;
}
return [super needsDisplayForKey:key];
}
Of course, you also need to have a #property called percentage. From now on you can animate the percentage property using core animation. I did not check whether it works using the [UIView animateWithDuration...] call as well. It might work. But this worked for me:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"percentage"];
animation.duration = 1.0;
animation.fromValue = [NSNumber numberWithDouble:0];
animation.toValue = [NSNumber numberWithDouble:100];
[myCustomLayer addAnimation:animation forKey:#"animatePercentage"];
Oh and to use yourCustomLayer with myCircleView, do this:
[myCircleView.layer addSublayer:myCustomLayer];
Complete Swift 3 example:
public class CircularProgressView: UIView {
public dynamic var progress: CGFloat = 0 {
didSet {
progressLayer.progress = progress
}
}
fileprivate var progressLayer: CircularProgressLayer {
return layer as! CircularProgressLayer
}
override public class var layerClass: AnyClass {
return CircularProgressLayer.self
}
override public func action(for layer: CALayer, forKey event: String) -> CAAction? {
if event == #keyPath(CircularProgressLayer.progress),
let action = action(for: layer, forKey: #keyPath(backgroundColor)) as? CAAnimation,
let animation: CABasicAnimation = (action.copy() as? CABasicAnimation) {
animation.keyPath = #keyPath(CircularProgressLayer.progress)
animation.fromValue = progressLayer.progress
animation.toValue = progress
self.layer.add(animation, forKey: #keyPath(CircularProgressLayer.progress))
return animation
}
return super.action(for: layer, forKey: event)
}
}
/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
#NSManaged var progress: CGFloat
let startAngle: CGFloat = 1.5 * .pi
let twoPi: CGFloat = 2 * .pi
let halfPi: CGFloat = .pi / 2
override class func needsDisplay(forKey key: String) -> Bool {
if key == #keyPath(progress) {
return true
}
return super.needsDisplay(forKey: key)
}
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
UIGraphicsPushContext(ctx)
//Light Grey
UIColor.lightGray.setStroke()
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let strokeWidth: CGFloat = 4
let radius = (bounds.size.width / 2) - strokeWidth
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
path.lineWidth = strokeWidth
path.stroke()
//Red
UIColor.red.setStroke()
let endAngle = (twoPi * progress) - halfPi
let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
pathProgress.lineWidth = strokeWidth
pathProgress.lineCapStyle = .round
pathProgress.stroke()
UIGraphicsPopContext()
}
}
let circularProgress = CircularProgressView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
circularProgress.progress = 0.76
}, completion: nil)
There is a great objc article here, which goes into details about how this works
As well as a objc project that uses the same concepts here:
Essentially action(for layer:) will be called when an object is being animated from an animation block, we can start our own animations with the same properties (stolen from the backgroundColor property) and animate the changes.
For the ones who needs more details on that like I did:
there is a cool example from Apple covering this question.
E.g. thanks to it I found that you don't actually need to add your custom layer as sublayer (as #Tom van Zummeren suggests). Instead it's enough to add a class method to your View class:
+ (Class)layerClass
{
return [CustomLayer class];
}
Hope it helps somebody.
you will have to implement the percentage part yourself. you can override layer drawing code to draw your cgpath accroding to the set percentage value. checkout the core animation programming guide and animation types and timing guide
#David Rees answer get me on the right track, but there is one issue. In my case
completion of animation always returns false, right after animation has began.
UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
circularProgress.progress = 0.76
}, completion: { finished in
// finished - always false
})
This is the way it've worked for me - action of animation is handled inside of CALayer.
I have also included small example how to make layer with additional properties like "color".
In this case, without initializer that copies the values, changing the color would take affect only on non-animating view. During animation it would be visble with "default setting".
public class CircularProgressView: UIView {
#objc public dynamic var progress: CGFloat {
get {
return progressLayer.progress
}
set {
progressLayer.progress = newValue
}
}
fileprivate var progressLayer: CircularProgressLayer {
return layer as! CircularProgressLayer
}
override public class var layerClass: AnyClass {
return CircularProgressLayer.self
}
}
/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
#NSManaged var progress: CGFloat
let startAngle: CGFloat = 1.5 * .pi
let twoPi: CGFloat = 2 * .pi
let halfPi: CGFloat = .pi / 2
var color: UIColor = .red
// preserve layer properties
// without this specyfic init, if color was changed to sth else
// animation would still use .red
override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? CircularProgressLayer {
self.color = layer.color
self.progress = layer.progress
}
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override class func needsDisplay(forKey key: String) -> Bool {
if key == #keyPath(progress) {
return true
}
return super.needsDisplay(forKey: key)
}
override func action(forKey event: String) -> CAAction? {
if event == #keyPath(CircularProgressLayer.progress) {
guard let animation = action(forKey: #keyPath(backgroundColor)) as? CABasicAnimation else {
setNeedsDisplay()
return nil
}
if let presentation = presentation() {
animation.keyPath = event
animation.fromValue = presentation.value(forKeyPath: event)
animation.toValue = nil
} else {
return nil
}
return animation
}
return super.action(forKey: event)
}
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
UIGraphicsPushContext(ctx)
//Light Gray
UIColor.lightGray.setStroke()
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let strokeWidth: CGFloat = 4
let radius = (bounds.size.width / 2) - strokeWidth
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
path.lineWidth = strokeWidth
path.stroke()
// Red - default
self.color.setStroke()
let endAngle = (twoPi * progress) - halfPi
let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
pathProgress.lineWidth = strokeWidth
pathProgress.lineCapStyle = .round
pathProgress.stroke()
UIGraphicsPopContext()
}
}
The way to handle animations differently and copy layer properties I have found in this article:
https://medium.com/better-programming/make-apis-like-apple-animatable-view-properties-in-swift-4349b2244cea
Related
I have a Timer() that asks the view to refresh every x seconds:
func updateTimer(_ stopwatch: Stopwatch) {
stopwatch.counter = stopwatch.counter + 0.035
Stopwatch.circlePercentage += 0.035
stopwatchViewOutlet.setNeedsDisplay()
}
--
class StopwatchView: UIView, UIGestureRecognizerDelegate {
let buttonClick = UITapGestureRecognizer()
override func draw(_ rect: CGRect) {
Stopwatch.drawStopwatchFor(view: self, gestureRecognizers: buttonClick)
}
}
--
extension Stopwatch {
static func drawStopwatchFor(view: UIView, gestureRecognizers: UITapGestureRecognizer) {
let scale: CGFloat = 0.8
let joltButtonView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 75, height: 75))
let imageView: UIImageView!
// -- Need to hook this to the actual timer --
let temporaryVariableForTimeIncrement = CGFloat(circlePercentage)
// Exterior of sphere:
let timerRadius = min(view.bounds.size.width, view.bounds.size.height) / 2 * scale
let timerCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
let path = UIBezierPath(arcCenter: timerCenter, radius: timerRadius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
path.lineWidth = 2.0
UIColor.blue.setStroke()
path.stroke()
// Interior of sphere
let startAngle = -CGFloat.pi / 2
let arc = CGFloat.pi * 2 * temporaryVariableForTimeIncrement / 100
let cPath = UIBezierPath()
cPath.move(to: timerCenter)
cPath.addLine(to: CGPoint(x: timerCenter.x + timerRadius * cos(startAngle), y: timerCenter.y))
cPath.addArc(withCenter: timerCenter, radius: timerRadius * CGFloat(0.99), startAngle: startAngle, endAngle: arc + startAngle, clockwise: true)
cPath.addLine(to: CGPoint(x: timerCenter.x, y: timerCenter.y))
let circleShape = CAShapeLayer()
circleShape.path = cPath.cgPath
circleShape.fillColor = UIColor.cyan.cgColor
view.layer.addSublayer(circleShape)
// Jolt button
joltButtonView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
joltButtonView.layer.cornerRadius = 38
joltButtonView.backgroundColor = UIColor.white
imageView = UIImageView(frame: joltButtonView.frame)
imageView.contentMode = .scaleAspectFit
imageView.image = image
joltButtonView.addGestureRecognizer(gestureRecognizers)
view.addSubview(joltButtonView)
view.addSubview(imageView)
}
}
My first problem is that the subviews are getting redrawn each time. The second one is that after a couple seconds, the performance starts to deteriorate really fast.
Too many instances of the subview
Trying to drive the blue graphic with a Timer()
Should I try to animate the circle percentage graphic instead of redrawing it each time the timer function is called?
The major observation is that you should not be adding subviews in draw. That is intended for rendering a single frame and you shouldn't be adding/removing things from the view hierarchy inside draw. Because you're adding subviews roughly ever 0.035 seconds, your view hierarchy is going to explode, with adverse memory and performance impact.
You should either have a draw method that merely calls stroke on your updated UIBezierPath for the seconds hand. Or, alternatively, if using CAShapeLayer, just update its path (and no draw method is needed at all).
So, a couple of peripheral observations:
You are incrementing your "percentage" for every tick of your timer. But you are not guaranteed the frequency with which your timer will be called. So, instead of incrementing some "percentage", you should save the start time when you start the timer, and then upon every tick of the timer, you should recalculate the amount of time elapsed between then and now when figuring out how much time has elapsed.
You are using a Timer which is good for most purposes, but for the sake of optimal drawing, you really should use a CADisplayLink, which is optimally timed to allow you to do whatever you need before the next refresh of the screen.
So, here is an example of a simple clock face with a sweeping second hand:
open class StopWatchView: UIView {
let faceLineWidth: CGFloat = 5 // LineWidth of the face
private var startTime: Date? { didSet { self.updateHand() } } // When was the stopwatch resumed
private var oldElapsed: TimeInterval? { didSet { self.updateHand() } } // How much time when stopwatch paused
public var elapsed: TimeInterval { // How much total time on stopwatch
guard let startTime = startTime else { return oldElapsed ?? 0 }
return Date().timeIntervalSince(startTime) + (oldElapsed ?? 0)
}
private weak var displayLink: CADisplayLink? // Display link animating second hand
public var isRunning: Bool { return displayLink != nil } // Is the timer running?
private var clockCenter: CGPoint { // Center of the clock face
return CGPoint(x: bounds.midX, y: bounds.midY)
}
private var radius: CGFloat { // Radius of the clock face
return (min(bounds.width, bounds.height) - faceLineWidth) / 2
}
private lazy var face: CAShapeLayer = { // Shape layer for clock face
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = self.faceLineWidth
shapeLayer.strokeColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1).cgColor
shapeLayer.fillColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor
return shapeLayer
}()
private lazy var hand: CAShapeLayer = { // Shape layer for second hand
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 3
shapeLayer.strokeColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1).cgColor
shapeLayer.fillColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor
return shapeLayer
}()
override public init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
// add necessary shape layers to layer hierarchy
private func configure() {
layer.addSublayer(face)
layer.addSublayer(hand)
}
// if laying out subviews, make sure to resize face and update hand
override open func layoutSubviews() {
super.layoutSubviews()
updateFace()
updateHand()
}
// stop display link when view disappears
//
// this prevents display link from keeping strong reference to view after view is removed
override open func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
pause()
}
}
// MARK: - DisplayLink routines
/// Start display link
open func resume() {
// cancel any existing display link, if any
pause()
// start new display link
startTime = Date()
let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink.add(to: .main, forMode: .commonModes)
// save reference to it
self.displayLink = displayLink
}
/// Stop display link
open func pause() {
displayLink?.invalidate()
// calculate floating point number of seconds
oldElapsed = elapsed
startTime = nil
}
open func reset() {
pause()
oldElapsed = nil
}
/// Display link handler
///
/// Will update path of second hand.
#objc func handleDisplayLink(_ displayLink: CADisplayLink) {
updateHand()
}
/// Update path of clock face
private func updateFace() {
face.path = UIBezierPath(arcCenter: clockCenter, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath
}
/// Update path of second hand
private func updateHand() {
// convert seconds to an angle (in radians) and figure out end point of seconds hand on the basis of that
let angle = CGFloat(elapsed / 60 * 2 * .pi - .pi / 2)
let endPoint = CGPoint(x: clockCenter.x + cos(angle) * radius * 0.9, y: clockCenter.y + sin(angle) * radius * 0.9)
// update path of hand
let path = UIBezierPath()
path.move(to: clockCenter)
path.addLine(to: endPoint)
hand.path = path.cgPath
}
}
And
class ViewController: UIViewController {
#IBOutlet weak var stopWatchView: StopWatchView!
#IBAction func didTapStartStopButton () {
if stopWatchView.isRunning {
stopWatchView.pause()
} else {
stopWatchView.resume()
}
}
#IBAction func didTapResetButton () {
stopWatchView.reset()
}
}
Now, in the above example, I'm just updating the CAShapeLayer of the seconds hand in my CADisplayLink handler. Like I said at the start, you can alternatively have a draw method that simply strokes the paths you need for single frame of animation and then call setNeedsDisplay in your display link handler. But if you do that, don't change the view hierarchy within draw, but rather do any configuration you need in init and draw should just stroke whatever the path should be at that moment.
I have written an custom control in Swift for IOS. The custom control is a circle with 4 segments in it, all with different colors. The goal of the control is to serve as some sort of "select tool". You rotate the circle and whatever color is on top is the selected color. The structure is as follows: There is one CircleLayer and in that CircleLayer there are 4 SegmentLayers all with different colors (See screenshot for example).
Rotating the circle works but the thing is that it's always rotating from the same point. For example when I click the circle on the red segment the circle rotates so that the green segment is where I just clicked.
Any suggestions to how I could make the control start rotating from where I clicked.
Current code for wheel control:
import UIKit
func degreesToRadians (value:Double) -> Double {
return value * M_PI / 180.0
}
func radiansToDegrees (value:Double) -> Double {
return value * 180.0 / M_PI
}
func square (value:CGFloat) -> CGFloat {
return value * value
}
#IBDesignable public class CircleControl: UIControl, RotateStartDelegate {
private var backingValue: CGFloat = 0.0
/** Layer renderer **/
private let circleRenderer = CircleRenderer()
/** Contains the receiver’s current value. */
public var value: CGFloat {
get { return backingValue }
set { setValue(newValue, animated: false) }
}
public var angle: Double = 0.0
/** Set the angle of the circle */
public func setValue(value: CGFloat, animated: Bool) {
if(value != self.value) {
self.backingValue = value
// Update human-readable angle
var a = radiansToDegrees(Double(value))
self.angle = (a >= 0) ? a : a + 360.0
// Set angle
circleRenderer.setCircleAngle(value, animated: animated)
sendActionsForControlEvents(.ValueChanged)
}
}
/** Contains a Boolean value indicating whether changes in the sliders value generate continuous update events. */
public var continuous = true
public override init(frame: CGRect) {
super.init(frame: frame)
createSubLayers()
let gr = RotationGestureRecognizer(delegate: self, target: self, action: "handleRotation:")
self.addGestureRecognizer(gr)
let tr = TapGestureRecognizer(target: self, action: "handleTap:")
self.addGestureRecognizer(tr)
self.setValue(circleRenderer.segmentMiddle, animated: false)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/** Set bounds of all the sub layers **/
func createSubLayers() {
circleRenderer.update(bounds)
layer.addSublayer(circleRenderer.circleLayer)
}
func rotationStart(startingPoint: CGPoint, angle: CGFloat) {
println("Rotation started")
println(startingPoint)
// circleRenderer.setDragStartingAngle(angle)
//
//// circleRenderer.circleLayer.anchorPoint = startingPoint
////
//// circleRenderer.backingPointerAngle = angle
//// circleRenderer.setCircleAngle(angle, animated: true)
}
/** Animate to the color usert tapped on **/
func handleTap(sender: AnyObject) {
let tr = sender as! TapGestureRecognizer
}
/** Update the angle **/
func handleRotation(sender: AnyObject) {
let gr = sender as! RotationGestureRecognizer
self.value = gr.rotation
// When the gesture has stopped make a small correction to the middle of the segment
if (gr.state == UIGestureRecognizerState.Ended) || (gr.state == UIGestureRecognizerState.Cancelled) {
var segmentSize:Double = 360 / 4
if self.angle >= 0.0 && self.angle < segmentSize {
self.setValue(circleRenderer.segmentMiddle, animated: true)
} else if self.angle >= segmentSize && self.angle < segmentSize * 2 {
self.setValue(circleRenderer.segmentMiddle * 3, animated: true)
} else if self.angle >= segmentSize * 2 && self.angle < segmentSize * 3 {
self.setValue(circleRenderer.segmentMiddle * -3, animated: true)
} else if self.angle >= segmentSize * 3 && self.angle < segmentSize * 4 {
self.setValue(circleRenderer.segmentMiddle * -1, animated: true)
}
}
}
}
private class CircleRenderer {
/** Angle properties **/
var backingPointerAngle: CGFloat = 0.0
var circleAngle: CGFloat {
get { return backingPointerAngle }
set { setCircleAngle(newValue, animated: false) }
}
/** Layers **/
let circleLayer = CALayer()
let seg1Layer = CAShapeLayer()
let seg2Layer = CAShapeLayer()
let seg3Layer = CAShapeLayer()
let seg4Layer = CAShapeLayer()
/** Segment size **/
let segmentSize:CGFloat = CGFloat( ( M_PI*2 ) / 4)
/** Middle of a segment. The angle to rotate to **/
let segmentMiddle:CGFloat = CGFloat(( M_PI*2 ) / 8)
/** Initialize the colors **/
init() {
seg1Layer.fillColor = UIColor.greenColor().CGColor!
seg2Layer.fillColor = UIColor(red: 204, green: 0, blue: 0, alpha: 100).CGColor!
seg3Layer.fillColor = UIColor(red: 255, green: 203, blue: 0, alpha: 100).CGColor!
seg4Layer.fillColor = UIColor.blueColor().CGColor!
circleLayer.opaque = true
circleLayer.backgroundColor = UIColor.clearColor().CGColor!
}
func setDragStartingAngle(angle: CGFloat) {
// Set orientation?
}
/** Change the angle of the circle, animated or not animated **/
func setCircleAngle(circleAngle: CGFloat, animated: Bool) {
CATransaction.begin()
CATransaction.setDisableActions(true)
circleLayer.transform = CATransform3DMakeRotation(circleAngle, 0.0, 0.0, 0.1)
if animated {
let midAngle = (max(circleAngle, self.circleAngle) - min(circleAngle, self.circleAngle) ) / 2.0 + min(circleAngle, self.circleAngle)
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.duration = 0.25
animation.values = [self.circleAngle, midAngle, circleAngle]
animation.keyTimes = [0.0, 0.5, 1.0]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleLayer.addAnimation(animation, forKey: "shake")
}
CATransaction.commit()
self.backingPointerAngle = circleAngle
}
/** Draw the segment layers paths **/
func update() {
let center = CGPoint(x: circleLayer.bounds.size.width / 2.0, y: circleLayer.bounds.size.height / 2.0)
let radius:CGFloat = min(circleLayer.bounds.size.width, circleLayer.bounds.size.height) / 2 * 1
let seg1Path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle: segmentSize, clockwise: true)
seg1Path.addLineToPoint(center)
seg1Layer.path = seg1Path.CGPath
let seg2Path = UIBezierPath(arcCenter: center, radius: radius, startAngle: segmentSize, endAngle: segmentSize*2, clockwise: true)
seg2Path.addLineToPoint(center)
seg2Layer.path = seg2Path.CGPath
let seg3Path = UIBezierPath(arcCenter: center, radius: radius, startAngle: segmentSize*2, endAngle: segmentSize*3, clockwise: true)
seg3Path.addLineToPoint(center)
seg3Layer.path = seg3Path.CGPath
let seg4Path = UIBezierPath(arcCenter: center, radius: radius, startAngle: segmentSize*3, endAngle: segmentSize*4, clockwise: true)
seg4Path.addLineToPoint(center)
seg4Layer.path = seg4Path.CGPath
}
/** Update the frame and position of the layers **/
func update(bounds: CGRect) {
let position = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
circleLayer.position = position
circleLayer.bounds = bounds
circleLayer.addSublayer(seg1Layer)
circleLayer.addSublayer(seg2Layer)
circleLayer.addSublayer(seg3Layer)
circleLayer.addSublayer(seg4Layer)
update()
}
}
import UIKit.UIGestureRecognizerSubclass
private class TapGestureRecognizer : UITapGestureRecognizer {
var rotation: CGFloat = 0.0
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
if let touch = touches[touches.startIndex] as? UITouch {
self.rotation = rotationForLocation(touch.locationInView(self.view))
}
}
func rotationForLocation(location: CGPoint) -> CGFloat {
let offset = CGPoint(x: location.x - view!.bounds.midX, y: location.y - view!.bounds.midY)
return atan2(offset.y, offset.x)
}
}
protocol RotateStartDelegate {
func rotationStart(startingPoint: CGPoint, angle: CGFloat)
}
private class RotationGestureRecognizer: UIPanGestureRecognizer {
/** Angle of rotation **/
var rotation: CGFloat = 0.0
var rotationStart: CGFloat = 0.0
var currentState: String = "idle"
var rotationDelegate: RotateStartDelegate
init(delegate: RotateStartDelegate, target: AnyObject, action: Selector) {
self.rotationDelegate = delegate
super.init(target: target, action: action)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
self.currentState = "begin"
if let touch = touches[touches.startIndex] as? UITouch {
self.rotationDelegate.rotationStart(touch.locationInView(self.view), angle: rotationForLocation(touch.locationInView(self.view)))
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
self.currentState = "dragging"
updateRotationWithTouches(touches)
}
override func touchesEnded(touches: Set<NSObject>!, withEvent event: UIEvent!) {
super.touchesEnded(touches, withEvent: event)
self.currentState = "idle"
}
func updateRotationWithTouches(touches: Set<NSObject>) {
if let touch = touches[touches.startIndex] as? UITouch {
self.rotation = rotationForLocation(touch.locationInView(self.view))
}
}
func rotationForLocation(location: CGPoint) -> CGFloat {
let offset = CGPoint(x: location.x - view!.bounds.midX, y: location.y - view!.bounds.midY)
return atan2(offset.y, offset.x)
}
}
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
}
}
}
I'm trying to animate a circle that is being drawn, I know how to do that, however, I do not seem to be able to find any information on how to trigger an animation after a button has been clicked or after data has been updated by a service.
The easiest solution for this would be to use CAShapeLayers. I need to update the time and then show that in the form of a few circles on top of each other.
I also have code to be able to do this in the drawRect method but I don't know yet which is the better solution for updating the circles. Do you guys know how to do this?
This is my code while using CAShapeLayers:
private var _greyCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeOneCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeTwoCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeThreeCircleLayer: CAShapeLayer = CAShapeLayer()
private var _transpartentOrangeFourCircleLayer: CAShapeLayer = CAShapeLayer()
private var _solidOrangeCircleLayer: CAShapeLayer = CAShapeLayer()
private var _currentDisplayedTime: Double = Double(0.0)
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
addCAShapeLayer(self._greyCircleLayer, colour: StyleGlobals.StrokeColor.CGColor)
addCAShapeLayer(self._transpartentOrangeOneCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeTwoCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeThreeCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._transpartentOrangeFourCircleLayer, colour: StyleGlobals.TransparentOrange.CGColor)
addCAShapeLayer(self._solidOrangeCircleLayer, colour: StyleGlobals.SolidOrange.CGColor)
}
And then I try to animate the layers with the following method, however it does not work. It only works when calling it after having added the layers to the view hierarchy:
func animateCircle(duration: NSTimeInterval, shapeLayer: CAShapeLayer, timeStart: CGFloat, timeEnd: CGFloat) {
/*//let duration = 1.0
let delay = 0.0 // delay will be 0.0 seconds (e.g. nothing)
let options = UIViewAnimationOptions.CurveEaseInOut // change the timing curve to `ease-in ease-out`
UIView.animateWithDuration(duration, delay: delay, options: options, animations: {
// any changes entered in this block will be animated
shapeLayer.strokeEnd = timeEnd
}, completion: { finished in
// any code entered here will be applied
// once the animation has completed
})*/
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = duration
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = timeStart
animation.toValue = timeEnd
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
shapeLayer.strokeEnd = timeEnd
// Do the actual animation
shapeLayer.addAnimation(animation, forKey: "strokeEnd")
}
normally a UIView will be added in the moment you add it with:
self.addSubView(viewToAdd);
If you have inserted your code for the animation inside your UIView (doesn't matter what kind of UIControl element it is ) you could trigger the drawing inside drawRect() with this:
viewToAdd.setNeedsDisplay();
setNeedsDisplay triggers the view to update itself and call the drawRect method which never should be called directly.
You could also let the view draw itself when it is ready. You can add the method didMoveToSuperView() inside your UIView and then call the setNeedsDisplay().
Is this what you're looking for?
class MyView: UIView {
override func didMoveToSuperview() {
println("Animate Me!")
}
}
So I finally found my answer in the following tutorial:
http://blog.pixelingene.com/2012/02/animating-pie-slices-using-a-custom-calayer/
Looking at the PieSliceLayer class, it shows how with observable fields you can animate the changes.
Also when adding the layer to the UIView class, you need to call setNeedsDisplay() on it to be able to show it. It does not show by default.
Below is my code:
class HourLayer: CAShapeLayer {
#NSManaged private var _startAngle: CGFloat
#NSManaged private var _endAngle: CGFloat
#NSManaged private var _fillColor: UIColor
#NSManaged private var _strokeWidth: CGFloat
#NSManaged private var _strokeColor: UIColor
#NSManaged private var _duration: CFTimeInterval
private var _previousEndAngle: CGFloat = 0.0
private var _previousStartAngle: CGFloat = 0.0
private var _nextLayerToAnimate: HourLayer?
private var _nextLayerToAnimateStartAngle: CGFloat?
private var _nextLayerToAnimateEndAngle: CGFloat?
private var _nextLayerToAnimateDuration: CFTimeInterval?
private let _lenghtOfArc: CGFloat = CGFloat(2 * M_PI)
internal var StartAngle: CGFloat {
get {
return _startAngle
}
set {
_startAngle = newValue
}
}
internal var EndAngle: CGFloat {
get {
return _endAngle
}
set {
_endAngle = newValue
}
}
internal var FillColor: UIColor {
get {
return _fillColor
}
set {
_fillColor = newValue
}
}
internal var StrokeWidth: CGFloat {
get {
return _strokeWidth
}
set {
_strokeWidth = newValue
}
}
internal var StrokeColor: UIColor {
get {
return _strokeColor
}
set {
_strokeColor = newValue
}
}
internal var DurationOfAnimation: CFTimeInterval {
get {
return _duration
}
set {
_duration = newValue
}
}
required override init!() {
super.init()
self._startAngle = 0.0
self._endAngle = 0.0
self._fillColor = UIColor.clearColor()
self._strokeWidth = 4.0
self._strokeColor = UIColor.blackColor()
self._duration = 1.0
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("required init(:coder) is missing")
}
override init!(layer: AnyObject!) {
super.init(layer: layer)
if layer.isKindOfClass(HourLayer) {
var other: HourLayer = layer as HourLayer
self._startAngle = other._startAngle
self._endAngle = other._endAngle
self._fillColor = other._fillColor
self._strokeWidth = other._strokeWidth
self._strokeColor = other._strokeColor
self._duration = other._duration
}
}
override var frame: CGRect {
didSet {
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
override func actionForKey(event: String!) -> CAAction! {
if event == "_startAngle" || event == "_endAngle" {
return makeAnimationForKey(event)
}
return super.actionForKey(event)
}
/*internal func prepareLayerForAnimationAfterThisLayer(layer: HourLayer, startAngle: CGFloat, endAngle: CGFloat, duration: CFTimeInterval) {
self._nextLayerToAnimate = layer
self._nextLayerToAnimateStartAngle = startAngle
self._nextLayerToAnimateEndAngle = endAngle
self._nextLayerToAnimateDuration = duration
}*/
private func makeAnimationForKey(event: String) -> CABasicAnimation {
// We want to animate the strokeEnd property of the circleLayer
let animation: CABasicAnimation = CABasicAnimation(keyPath: event)
// Set the animation duration appropriately
animation.duration = self._duration
// When no animation has been triggered and the presentation layer does not exist yet.
if self.presentationLayer() == nil {
if event == "_startAngle" {
animation.fromValue = self._previousStartAngle
self._previousStartAngle = self._startAngle
} else if event == "_endAngle" {
animation.fromValue = self._previousEndAngle
self._previousEndAngle = self._endAngle
}
} else {
animation.fromValue = self.presentationLayer()!.valueForKey(event)
}
animation.delegate = self
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animation
}
override class func needsDisplayForKey(key: String) -> Bool {
if key == "_startAngle" || key == "_endAngle" {
return true
}
return super.needsDisplayForKey(key)
}
override func drawInContext(ctx: CGContext!) {
var center: CGPoint = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)
var radius: CGFloat = CGFloat((CGFloat(self.bounds.width) - CGFloat(_strokeWidth)) / 2)
// Set the stroke color
CGContextSetStrokeColorWithColor(ctx, _strokeColor.CGColor)
// Set the line width
CGContextSetLineWidth(ctx, _strokeWidth)
// Set the fill color (if you are filling the circle)
CGContextSetFillColorWithColor(ctx, UIColor.clearColor().CGColor)
// Draw the arc around the circle
CGContextAddArc(ctx, center.x, center.y, radius, _startAngle, _lenghtOfArc * _endAngle, 0)
// Draw the arc
CGContextDrawPath(ctx, kCGPathStroke) // or kCGPathFillStroke to fill and stroke the circle
super.drawInContext(ctx)
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
// Trigger animation for other layer by setting their values for _startAngle and _endAngle.
/*if flag && _nextLayerToAnimate != nil && _nextLayerToAnimateStartAngle != nil && _nextLayerToAnimateEndAngle != nil && _nextLayerToAnimateDuration != nil {
self._nextLayerToAnimate!._startAngle = _nextLayerToAnimateStartAngle!
self._nextLayerToAnimate!._endAngle = _nextLayerToAnimateEndAngle!
self._nextLayerToAnimate!._duration = _nextLayerToAnimateDuration!
}*/
}
I have however the problem of not knowing which layer is animating and which layer should succeed it. Now trying to figure this out in the following question:
Swift: Animate layers in sequence from UIView
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.