うずの中を小さいボールがくるくるするiPhoneアプリのサンプルコードを描いてみます。
import UIKit
class ViewController: UIViewController {
var spiral = CAShapeLayer()
var box = Array<CAShapeLayer>()
override func viewDidLoad() {
super.viewDidLoad()
self.createSpiral()
self.createColorBalls()
}
func createSpiral() {
var r = 0.0, s = 0.0, e = 0.0
var path = UIBezierPath()
var o = CGPointZero
path.moveToPoint(o)
for i in 0…40 {
r = Double(i * 4.0)
s = Double(i%4) * M_PI_2
e = Double(i%4) * M_PI_2 + M_PI_2
o = CGPointMake(o.x – CGFloat(4.0 * cos(s)), o.y – CGFloat(4.0 * sin(s)))
path.addArcWithCenter(o, radius: CGFloat(r), startAngle: CGFloat(s), endAngle: CGFloat(e), clockwise: true)
}
self.spiral = CAShapeLayer()
self.spiral.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))
self.spiral.path = path.CGPath
self.spiral.fillColor = UIColor.clearColor().CGColor
self.spiral.strokeColor = UIColor.lightGrayColor().CGColor
self.view.layer.addSublayer(spiral)
}
func createColorBalls() {
for i in 0…5 {
var ball = self.createBall(UIColor(hue: CGFloat(i) * 0.2, saturation: 0.6, brightness: 0.9, alpha: 1.0))
}
}
func createBall(color: UIColor) -> CAShapeLayer
{
var path = UIBezierPath(arcCenter: CGPointZero, radius: CGFloat(5), startAngle: CGFloat(0), endAngle: CGFloat(2.0*M_PI), clockwise: true)
var ball = CAShapeLayer()
ball.path = path.CGPath
ball.fillColor = color.CGColor
ball.position = CGPoint(x: 10.0, y: CGRectGetMaxY(self.view.bounds) – 120.0)
self.view.layer.addSublayer(ball)
self.box.map({$0.position.x += 10})
self.box.append(ball)
return ball
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var ball = self.box.removeAtIndex(0)
var animation = CAKeyframeAnimation(keyPath: “position”)
animation.speed = 0.01
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
var transform = CGAffineTransformMakeTranslation(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))
animation.path = CGPathCreateCopyByTransformingPath(self.spiral.path, &transform)
ball.addAnimation(animation, forKey: nil)
var n = CGFloat((arc4random() % 10)) * 0.1
self.createBall(UIColor(hue: n, saturation: 0.6, brightness: 0.9, alpha: 1))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}