Skip to content

Instantly share code, notes, and snippets.

@alsedi
alsedi / gist:64954a98bd44d1b5675002b3781f0954
Created April 5, 2018 15:02
UIView+SizeConstraints.Swift
import Foundation
extension UIView {
func height(constant: CGFloat) {
setConstraint(value: constant, attribute: .height)
}
func width(constant: CGFloat) {
setConstraint(value: constant, attribute: .width)
}
func animate(duration:TimeInterval, delay:TimeInterval) {
let animation = CAKeyframeAnimation(keyPath: "path")
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.66, 0.86, 0.11, 0.95)
animation.keyTimes = [0.0, 0.2, 0.6, 1.0]
animation.values = [circlePath, circlePath, rectangleShape, rectangleShape]
animation.beginTime = delay
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.repeatCount = Float.infinity
let progressShape = CAShapeLayer()
let backgroundShape = CAShapeLayer()
var percent = 0.5
private var shapes = [MutableShapeLayer]()
private let minimalSize = CGSize(width: 50, height: 50)
var step: CGFloat = 55.0
var shapeWidth: CGFloat = 20
var shapesCount:Int = 5
let color = UIColor(hue: 181/360.0 + CGFloat(Double(i)/500.0), saturation: 0.96, brightness: 0.88 , alpha: 1)
private func generateShapes() {
for i in 0..<shapesCount * 2 - 1 {
let shape = MutableShapeLayer()
shape.setup(size: minimalSize + ((step / 2.0) * CGFloat(i)), center: center, thickness: shapeWidth, color: (i % 2 == 0) ? UIColor.black : UIColor.white)
shapes.append(shape)
layer.insertSublayer(shape, at: 0)
}
}
func animate() {
if shapes.count == 0 {
generateShapes()
}
for i in 0..<shapes.count {
let delay = (i % 2 == 0) ? Double(i+1)/5.5 : Double(i+1)/5.505
shapes[i].animate(duration: 5.0, delay: delay)
}
}
func setup(size:CGSize, center:CGPoint, thickness: CGFloat, color:UIColor) {
// 0
frame = CGRect(origin: CGPoint.zero, size: size)
position = center
// 1
path = circlePath
lineWidth = thickness
// 2
strokeColor = color.cgColor
fillColor = UIColor.clear.cgColor
let center = CGPoint(x: bounds.midX, y: bounds.midY)
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: center.x, y: center.y)
transform = transform.rotated(by: -CGFloat(M_PI_2 + M_PI_4))
transform = transform.translatedBy(x: -center.x, y: -center.y)
circle.apply(transform)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let shapeView = MutableShapeView(frame: view.frame)
view.addSubview(shapeView)
shapeView.animate()
}