Last active
May 6, 2018 06:54
-
-
Save tanakeiQ/93d31ddc6bf45fc8ec0f0c2a4afcbaea to your computer and use it in GitHub Desktop.
Circle Gauge Animation Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Refs: https://qiita.com/uin010bm/items/ff934d070d43a4666dbc | |
// Author: https://qiita.com/uin010bm | |
//Confirmed on Xcode 9.3(Swift 4.3) | |
//Change extenstion `swift` to `playground`. | |
import UIKit | |
import PlaygroundSupport | |
// CAShapeLayerインスタンスを生成 | |
var circle: CAShapeLayer = CAShapeLayer() | |
let view = UIView(frame: CGRect(x: 100, y: 100, width: 500, height: 500)) | |
// ※前提条件としてtargetViewが正方形であること | |
func drawCircle(_ targetView: UIView) { | |
// ゲージ幅 | |
let lineWidth: CGFloat = 10 | |
// 描画領域のwidth | |
let viewScale: CGFloat = targetView.frame.size.width | |
// 円のサイズ | |
let radius: CGFloat = viewScale - lineWidth | |
// 円の描画path設定 | |
circle.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: radius, height: radius), cornerRadius: radius / 2).cgPath | |
// 円のポジション設定 | |
circle.position = CGPoint(x: lineWidth / 2, y: lineWidth / 2) | |
// 塗りの色を設定 | |
circle.fillColor = UIColor.lightGray.cgColor | |
// 線の色を設定 | |
circle.strokeColor = UIColor.gray.cgColor | |
// 線の幅を設定 | |
circle.lineWidth = lineWidth | |
// 該当のUIViewのlayerにsublayerとしてCALayerを追加 | |
targetView.layer.addSublayer(circle) | |
// duration0.0のアニメーションにて初期描画(線が書かれていない状態)にしておく | |
drawCircleAnimation(key: "strokeEnd", animeName: "updateGageAnimation", fromValue: 0.0, toValue: 0.8, duration: 2.0, repeatCount: 1.0, flag: false) | |
} | |
func drawCircleAnimation(key: String, animeName: String, fromValue: CGFloat, toValue: CGFloat, duration: TimeInterval, repeatCount: Float, flag: Bool) { | |
// アニメーションkeyを設定 | |
let drawAnimation = CABasicAnimation(keyPath: key) | |
// アニメーション間隔の指定 | |
drawAnimation.duration = duration // "animate over 10 seconds or so.." | |
// 繰り返し回数の指定 | |
drawAnimation.repeatCount = repeatCount | |
// 起点と目標点の変化比率を設定 (0.0 〜 1.0) | |
drawAnimation.fromValue = fromValue | |
drawAnimation.toValue = toValue | |
// イージングを決定 | |
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) | |
// アニメ完了時の描画を保持 | |
drawAnimation.isRemovedOnCompletion = false | |
drawAnimation.fillMode = kCAFillModeForwards | |
// 逆再生の指定 | |
drawAnimation.autoreverses = flag | |
// Add the animation to the circle | |
circle.add(drawAnimation, forKey: animeName) | |
} | |
drawCircle(view) | |
view.backgroundColor = .white | |
PlaygroundPage.current.liveView = view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment