Created
August 23, 2018 08:37
-
-
Save vtourraine/b306fe962cb359f7b5b55db80372d54c to your computer and use it in GitHub Desktop.
View with clouds floating by.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CloudsView.swift | |
// | |
// Swift 4.2 | |
// | |
import UIKit | |
@available(iOS 10.0, *) | |
class CloudsView: UIView { | |
static let SpawnTimeInterval: TimeInterval = 10 | |
static let HorizontalRandomMaxOverflow: CGFloat = 200 | |
static let CloudSize: CGSize = CGSize(width: 84, height: 54) | |
static let AnimationDuration: TimeInterval = 50 | |
var animationTimer: Timer? | |
func startAnimation() { | |
guard animationTimer == nil else { | |
return | |
} | |
spawnBunchOfCloudsInTheSky() | |
spawnCloudFromTheSide() | |
animationTimer = Timer.scheduledTimer(withTimeInterval: CloudsView.SpawnTimeInterval, repeats: true) { (timer) in | |
self.spawnCloudFromTheSide() | |
} | |
} | |
override func removeFromSuperview() { | |
super.removeFromSuperview() | |
if let animationTimer = animationTimer { | |
animationTimer.invalidate() | |
} | |
} | |
func spawnBunchOfCloudsInTheSky() { | |
let InitialNumberOfClouds = Int.random(in: 2...3) | |
for _ in 0..<InitialNumberOfClouds { | |
spawnCloudInTheSky() | |
} | |
} | |
func spawnCloudInTheSky() { | |
spawnCloud(x: CGFloat.random(in: 0..<self.bounds.size.width)) | |
} | |
func spawnCloudFromTheSide() { | |
spawnCloud(x: CGFloat.random(in: -CloudsView.HorizontalRandomMaxOverflow..<0)) | |
} | |
func spawnCloud(x: CGFloat) { | |
let y = CGFloat.random(in: (CloudsView.CloudSize.height / 2)..<(self.bounds.size.height - CloudsView.CloudSize.height / 2)) | |
spawnCloud(origin: CGPoint(x: x, y: y)) | |
} | |
func spawnCloud(origin: CGPoint) { | |
let imageView = UIImageView(image: UIImage(named: "Cloud")) | |
imageView.tintColor = .white | |
imageView.alpha = 0.7 | |
imageView.frame = CGRect(origin: .zero, size: CloudsView.CloudSize) | |
imageView.center = origin | |
addSubview(imageView) | |
let boundsWidth = self.bounds.size.width | |
UIView.animate(withDuration: CloudsView.AnimationDuration, delay: 0, options: .curveLinear, animations: { | |
imageView.center = CGPoint(x: origin.x + boundsWidth + CloudsView.CloudSize.width + CloudsView.HorizontalRandomMaxOverflow, y: origin.y) | |
}) { (completed) in | |
if completed { | |
imageView.removeFromSuperview() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment