以下是每5秒钟在不同图像之间自动转换的代码。我想在转场中添加动画,即淡入淡出,从左侧滚动等等。我将如何在Swift中执行此操作?感谢。
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.animationImages = [
UIImage(named: "brooklyn-bridge.jpg")!,
UIImage(named: "grand-central-terminal.jpg")!,
UIImage(named: "new-york-city.jpg")!,
UIImage(named: "one-world-trade-center.jpg")!,
UIImage(named: "rain.jpg")!,
UIImage(named: "wall-street.jpg")!]
imageView.animationDuration = 25.0
imageView.startAnimating()
}
答案 0 :(得分:33)
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
let images = [
UIImage(named: "brooklyn-bridge.jpg")!,
UIImage(named: "grand-central-terminal.jpg")!,
UIImage(named: "new-york-city.jpg"),
UIImage(named: "one-world-trade-center.jpg")!,
UIImage(named: "rain.jpg")!,
UIImage(named: "wall-street.jpg")!]
var index = 0
let animationDuration: NSTimeInterval = 0.25
let switchingInterval: NSTimeInterval = 3
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = images[index++]
animateImageView()
}
func animateImageView() {
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
CATransaction.setCompletionBlock {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
self.animateImageView()
}
}
let transition = CATransition()
transition.type = kCATransitionFade
/*
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
*/
imageView.layer.addAnimation(transition, forKey: kCATransition)
imageView.image = images[index]
CATransaction.commit()
index = index < images.count - 1 ? index + 1 : 0
}
}
将其实现为自定义图像视图会更好。
答案 1 :(得分:4)
基于this answer的动画代码,在 Swift 3
中let animationDuration: TimeInterval = 0.25
let switchingInterval: TimeInterval = 3
func animateImageView()
{
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
CATransaction.setCompletionBlock {
DispatchQueue.main.asyncAfter(deadline: .now() + self.switchingInterval) {
self.animateImageView()
}
}
let transition = CATransition()
transition.type = kCATransitionFade
/*
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromRight
*/
imageView.layer.add(transition, forKey: kCATransition)
imageView.image = images.object(at: index) as! UIImage
CATransaction.commit()
index = index < images.count - 1 ? index + 1 : 0
}
答案 2 :(得分:3)
这是一个独立的类,可用于使用淡入淡出动画为图像更改设置动画。
class FadeImageView: UIImageView
{
@IBInspectable
var fadeDuration: Double = 0.13
override var image: UIImage?
{
get {
return super.image
}
set(newImage)
{
if let img = newImage
{
CATransaction.begin()
CATransaction.setAnimationDuration(self.fadeDuration)
let transition = CATransition()
transition.type = kCATransitionFade
super.layer.add(transition, forKey: kCATransition)
super.image = img
CATransaction.commit()
}
else {
super.image = nil
}
}
}
}