import UIKit
class UIClockView: UIView
{
var secLayer: CAShapeLayer!
var minLayer: CAShapeLayer!
var hourLayer: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
addHourLayer()
addMinLayer()
addSecLayer()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addHourLayer()
addMinLayer()
addSecLayer()
}
func drawClock()
{
let date = Date()
let calendar = Calendar.current
let hour = Int(calendar.component(.hour, from: date))
let min = Int(calendar.component(.minute, from: date))
let sec = Int(calendar.component(.second, from: date))
drawHourLayer(hour: hour, min: min)
drawMinLayer(min: min, sec: sec)
drawSecLayer(sec: sec)
}
func addHourLayer()
{
hourLayer = CAShapeLayer()
hourLayer.isHidden = true
hourLayer.strokeColor = UIColor.red.cgColor
hourLayer.lineWidth = 5.0
let line = CGMutablePath()
line.move(to: CGPoint(x:0,y:0))
line.addLine(to:CGPoint(x:80,y:0))
hourLayer.path = line
self.layer.addSublayer(hourLayer)
}
func drawHourLayer(hour: Int, min: Int)
{
let radian = 2.0 * CGFloat.pi * (CGFloat(hour) + CGFloat(min) / 60.0) / 12.0 - 0.5 * CGFloat.pi;
let translation = CGAffineTransform(translationX: self.bounds.width/2, y: self.bounds.height/2)
let rotation = CGAffineTransform(rotationAngle: radian)
let trans = rotation.concatenating(translation)
hourLayer.setAffineTransform(trans)
hourLayer.isHidden = false
}
func addMinLayer()
{
minLayer = CAShapeLayer()
minLayer.isHidden = true
minLayer.strokeColor = UIColor.blue.cgColor
minLayer.lineWidth = 3.0
let line = CGMutablePath()
line.move(to: CGPoint(x:0,y:0))
line.addLine(to:CGPoint(x:80,y:0))
minLayer.path = line
self.layer.addSublayer(minLayer)
}
func drawMinLayer(min: Int, sec: Int)
{
let radian = (2.0 * CGFloat.pi * CGFloat(min) + CGFloat(sec) / 60.0) / 60.0 - 0.5 * CGFloat.pi;
let translation = CGAffineTransform(translationX: self.bounds.width/2, y: self.bounds.height/2)
let rotation = CGAffineTransform(rotationAngle: radian)
let trans = rotation.concatenating(translation)
minLayer.setAffineTransform(trans)
minLayer.isHidden = false
}
func addSecLayer()
{
secLayer = CAShapeLayer()
secLayer.isHidden = true
secLayer.strokeColor = UIColor.black.cgColor
secLayer.lineWidth = 1.0
let line = CGMutablePath()
line.move(to: CGPoint(x:0,y:0))
line.addLine(to:CGPoint(x:100,y:0))
secLayer.path = line
self.layer.addSublayer(secLayer)
}
func drawSecLayer(sec: Int)
{
let radian = 2.0 * CGFloat.pi * CGFloat(sec) / 60.0 - 0.5 * CGFloat.pi;
let translation = CGAffineTransform(translationX: self.bounds.width/2, y: self.bounds.height/2)
let rotation = CGAffineTransform(rotationAngle: radian)
let trans = rotation.concatenating(translation)
secLayer.setAffineTransform(trans)
secLayer.isHidden = false
}
}