Skip to content

Instantly share code, notes, and snippets.

@jfamiglietti
Last active May 2, 2016 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfamiglietti/56b8c1c7464ffa3f552bd717ecc90e28 to your computer and use it in GitHub Desktop.
Save jfamiglietti/56b8c1c7464ffa3f552bd717ecc90e28 to your computer and use it in GitHub Desktop.
Creates a series of images for an animation similar to UIActivityIndicatorView
import UIKit
private extension CGPoint {
/// Multiplies point by given value
/// - parameter value: The x and y coordinates are multipled by this value.
/// - returns: A new CGPoint whose coordinate components have been multiplied by `value`
func multipliedBy(value: CGFloat) -> CGPoint {
return CGPoint(x: self.x * value, y: self.y * value)
}
}
/// Creates an array of images for a spinning wait indicator.
/// On iOS, we have UIActivityIndicatorView, but since this is unavailble on WatchOS,
/// we can create a similar-looking view by passing an animated UIImage to WKInterfaceImage.
/// - parameter radius: Radius of the spinning indicator.
/// - returns: An array of images to be used in a spinning wait indicator animation.
/// The width and height of the generated images will be 2x the given radius.
func generateSpinningWaitImagesWithRadius(radius: CGFloat) -> [UIImage] {
let startRadius = radius * 0.5
let lineWidth = radius / 5
let endRadius = radius - lineWidth / 2
let diameter = radius * 2
let ticks = (0..<12).map { (tickIndex: Int) -> CGFloat in
return CGFloat(Double(tickIndex) * (M_PI / 6))
}
return ticks.map { (angle: CGFloat) -> UIImage in
UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)
defer {
UIGraphicsEndImageContext()
}
for tick in ticks {
UIColor(white: tick / ticks.last!, alpha: 1).setStroke()
let unitPoint = CGPoint(x: cos(tick), y: sin(tick))
let tickMark = UIBezierPath()
tickMark.lineWidth = lineWidth
tickMark.lineCapStyle = .Round
tickMark.lineJoinStyle = .Round
tickMark.moveToPoint(unitPoint.multipliedBy(startRadius))
tickMark.addLineToPoint(unitPoint.multipliedBy(endRadius))
tickMark.applyTransform(CGAffineTransformMakeRotation(angle))
tickMark.applyTransform(CGAffineTransformMakeTranslation(radius, radius))
tickMark.stroke()
}
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment