我正在尝试在Swift中创建指针效果。我有六个UIImageView,每个都有一个以循环方式排序的UIImage。我想创建一个动画,让每个图像闪烁一段时间(就好像它是一个指针指示)。
我想过创建一个带有透明版图像的数组,然后从中创建一个动画序列,但持续时间会混淆。
这是我想要实现的想法。我希望这些图像能够逐一产生这种闪烁效果。
答案 0 :(得分:1)
这就是我将视图放在圆圈中并使它们“闪现”的方法。
首先我创建了常规视图(我不想使用ImageView,但您可以根据需要更改代码)..
我计算了需要围绕具有一定半径的中心点放置视图的角度,以使它们放置在一个圆圈中。
接下来我创建一个动画功能,它既有正向动画又有反向动画(我无法使autoreverses
标志起作用)..
要让一个人在另一个之后显示,我只需添加一个延迟(x2因为正向+反向)..
为了弄清楚所有动画何时完成,我将整个功能包裹在CATransaction
中。
注意:如果您不需要圆形展示位置代码,只需将其删除即可。 AFAIK,你只需要动画代码。
//
// ViewController.swift
// TestSO
//
// Created by Brandon on 2018-03-03.
// Copyright © 2018 XIO. All rights reserved.
//
import UIKit
extension UIColor {
class func random() -> UIColor {
let rand = { (max: CGFloat) -> CGFloat in
let rnd = CGFloat(arc4random()) / CGFloat(UInt32.max)
return rnd * max
}
return UIColor(red: rand(1.0), green: rand(1.0), blue: rand(1.0), alpha: 1.0)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let makeView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.random()
view.frame = CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)
self.view.addSubview(view)
return view
}
let imageViews = [
makeView(),
makeView(),
makeView(),
makeView(),
makeView(),
makeView()
]
let locationForView = { (angle: CGFloat, center: CGPoint, radius: CGFloat) -> CGPoint in
let angle = angle * CGFloat.pi / 180.0
return CGPoint(x: center.x - radius * cos(angle), y: center.y + radius * sin(angle))
}
for i in 0..<imageViews.count {
let center = self.view.center
let radius = ((150.0 + imageViews[i].bounds.size.width) / 2.0)
let count = imageViews.count
imageViews[i].center = locationForView(((360.0 / CGFloat(count)) * CGFloat(i)) + 90.0, center, radius)
}
self.animate(views: imageViews.reversed(), duration: 3.0, intervalDelay: 0.5)
}
private func animate(views: [UIView], duration: TimeInterval, intervalDelay: TimeInterval) {
CATransaction.begin()
CATransaction.setCompletionBlock {
print("COMPLETED ALL ANIMATIONS")
}
var delay: TimeInterval = 0.0
let interval = duration / TimeInterval(views.count)
for view in views {
let colour = view.backgroundColor
let transform = view.transform
UIView.animate(withDuration: interval, delay: delay, options: [.curveEaseIn], animations: {
view.backgroundColor = UIColor.red
view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: { (finished) in
UIView.animate(withDuration: interval, delay: 0.0, options: [.curveEaseIn], animations: {
view.backgroundColor = colour
view.transform = transform
}, completion: { (finished) in
})
})
delay += (interval * 2.0) + intervalDelay
}
CATransaction.commit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}