//
// ClockViewController.swift
// eee
//
// Created by admin on 2022/8/1.
//
// 钟表
import UIKit
class ClockViewController: MainViewController {
// 面板
lazy var dialLayer: CALayer = {
let layer = CALayer()
layer.bounds = CGRect(x: 0, y: 0, width: 200, height: 200)
layer.position = self.view.center
layer.contents = UIImage(named: "clock")?.cgImage
layer.backgroundColor = UIColor.red.cgColor
return layer
}()
// 秒针
lazy var secondHandView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.red
view.bounds = CGRect(x: 0, y: 0, width: 1, height: 70)
view.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
view.center = self.view.center
view.layer.allowsEdgeAntialiasing = true
return view
}()
// 分针
lazy var minuteHandView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.darkGray
view.bounds = CGRect(x: 0, y: 0, width: 3, height: 70)
view.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
view.center = self.view.center
view.layer.allowsEdgeAntialiasing = true
return view
}()
// 时针
lazy var hourHandView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.darkGray
view.bounds = CGRect(x: 0, y: 0, width: 4, height: 50)
view.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
view.center = self.view.center
view.layer.allowsEdgeAntialiasing = true
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "时钟动画"
self.view.layer.addSublayer(self.dialLayer)
self.view.addSubview(self.hourHandView)
self.view.addSubview(self.minuteHandView)
self.view.addSubview(self.secondHandView)
let link = CADisplayLink(target: self, selector: #selector(clockRunning))
link.add(to: RunLoop.main, forMode: RunLoop.Mode.default)
}
@objc func clockRunning(){
let tzone = TimeZone.current
var calender = NSCalendar.current
calender.timeZone = tzone
let currentDate = Date()
let cuttentTime = calender.dateComponents([.second,.hour,.minute], from: currentDate)
// 秒针
let angle = ( Double.pi * 2 / 60 ) * Double.init(cuttentTime.second ?? 0)
self.secondHandView.transform = CGAffineTransform(rotationAngle: angle)
// 分针
let minuteangle = ( Double.pi * 2 / 60 ) * Double.init(cuttentTime.minute ?? 0)
let secondToMinute = ( Double.pi * 2 / 60 ) * (Double.init(cuttentTime.second ?? 0) / 60)
self.minuteHandView.transform = CGAffineTransform(rotationAngle: minuteangle + secondToMinute)
// 时针
let hourangle = ( Double.pi * 2 / 12 ) * Double.init(cuttentTime.hour ?? 0)
let minuteToHour = ( Double.pi * 2 / 12 ) * (Double.init((cuttentTime.minute ?? 0) ) / 60)
self.hourHandView.transform = CGAffineTransform(rotationAngle: hourangle + minuteToHour)
}
}
【Swift】时钟动画
最新推荐文章于 2024-05-24 09:52:11 发布
这个博客展示了如何使用Swift创建一个实时更新的钟表动画,包括秒针、分针和时针的旋转效果。通过CADisplayLink实现定时更新,并利用Core Animation调整视图角度以模拟钟表指针的运动。
摘要由CSDN通过智能技术生成