円周上に一定の間隔で点を打っていくiPhoneアプリのサンプルコードを描いてみます。
import UIKit
class ViewController: UIViewController {
weak var mlabel : UILabel?
weak var lines : CAShapeLayer?
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(hue: 0.5, saturation: 0.05, brightness: 1, alpha: 1)
self.createTitle()
self.createCircle()
}
func createTitle() {
var l = UILabel()
l.font = UIFont(name: “Chalkduster”, size: 30)
l.text = “Round 0 % 12″
l.sizeToFit()
l.textColor = UIColor(hue: 0.3, saturation: 0.3, brightness: 1, alpha: 1)
l.center = CGPoint(x: CGRectGetMidX(self.view.bounds), y: 100)
self.view.addSubview(l)
self.mlabel = l
}
func createCircle() {
var w = CGRectGetMaxX(self.view.bounds) * 0.95
var h = w
var path = UIBezierPath(arcCenter: CGPointZero, radius: w * 0.5, startAngle: 0.0, endAngle: 2.0 * CGFloat(M_PI), clockwise: false)
var circle = CAShapeLayer()
circle.path = path.CGPath
circle.position = CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds))
circle.strokeColor = UIColor(hue: 0.1, saturation: 0.3, brightness: 1, alpha: 1).CGColor
circle.lineWidth = 5
circle.fillColor = UIColor.whiteColor().colorWithAlphaComponent(0.2).CGColor
self.view.layer.addSublayer(circle)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.count = (self.count + 1) % 12
self.showLines()
}
func showLines() {
if var dots = self.view.layer.sublayers as? [CALayer] {
for dot in dots.filter({(l : CALayer) -> Bool in l.name != nil }) {
dot.removeFromSuperlayer()
}
}
var dAngle = M_PI / 6.0
var r = Double(CGRectGetMidX(self.view.bounds) * 0.95)
var o = CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds))
var arr = [CALayer]()
for var i=0; i<12; ++i {
var idx = Double((self.count * i) % 12)
var x = r * cos(dAngle * idx)
var y = r * sin(dAngle * idx)
var dot = CALayer()
dot.name = “dot”
dot.frame = CGRectMake(0, 0, 8, 8)
dot.position = CGPoint(x: CGFloat(x)+o.x, y: CGFloat(y)+o.y)
dot.cornerRadius = 4
dot.backgroundColor = UIColor(hue: 0.1, saturation: 0.4, brightness: 0.7, alpha: 1).CGColor
self.view.layer.addSublayer(dot)
arr.append(dot)
}
if let l = self.mlabel {
l.text = NSString(format: “Round %d %% 12″, self.count)
l.sizeToFit()
}
var linePath = UIBezierPath()
for target in arr {
let others = arr.filter {$0 != target}
for other in others {
linePath.moveToPoint(target.position)
linePath.addLineToPoint(other.position)
}
}
if self.lines == nil {
var l = CAShapeLayer()
l.strokeColor = UIColor(hue: 0.4, saturation: 0.6, brightness: 0.7, alpha: 1).CGColor
l.lineWidth = 2
l.fillColor = UIColor.clearColor().CGColor
self.view.layer.addSublayer(l)
self.lines = l
}
self.lines!.path = linePath.CGPath
self.lines!.didChangeValueForKey(“path”)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}