Creating something new it’s a very interesting process - u can try to do one thing and, often, while u reach the target u can learn a lot of new stuff.
In the last project, we have a design that shows some insects on gradient background. We can improve this by adding some animations - for both insects and gradients.
Off cause, Customer may not want this, but we can do it just for fun, for exploring some stuff.
We can divide this task into a few parts:
animating gradient
animating insects
animating insects moving with path
animating gradient
Probably the easiest part, especially with SwiftUI. All that we need - is to use LinearGradient as background and animate colors on it.
We also need to add animation for it, to do so, we can use hueRotation and saturation modifiers:
And to make it even more interesting - we can scaleIn-scaleOut the gradient view:
AnimatedGradientView code
And the most interesting part - demo:
animating insects
The next part is to show insects - mosquitos in the background, that are flying. To do so we can use a few approaches - use video, use gif, or some other alternatives like a set of png or 3rd party Lottie.
We can increase the count of the mosquitos by simply creating some loops and changing the position. But it would be great if we can make them movable over the screen, like a real one ;]
animating insects moving with path
If we think about this task, we can divide it into a few parts:
move gif of mosquitos over the path and rotate them according to selected path direction
generate for each mosquito unique path and repeat follow infinitely
generate a lot of mosquitos
Thus I use SwiftUI here, I need to find a way how we can do all these steps.
For UIKit ist’s actually very simple task - we can user CoreAnimation and "position" property to animate something over the path.
With SwiftUI we have alternative methods that, as usual, have poor documentation. For this trick, we can use GeometryEffect.
I wrote separate article about it, available here and here.
I used code prepared by swiftui-lab for this case:
FollowEffect code
But the tricky part here - is to make each element (mosquito) move with a different path and with different speeds and with different timing…
If we use one view - then, all animations will be controlled with the same parameter (@State). This is not a good approach - the result will be either same for all instances of mosquitos either with the unpredictable result (for example if we use different timing for every instance and one view for all instances - thus SwiftUI use struct and so 1 @State is about to control all animations - the last instance will be the master one, all other … well - somehow…)
To solve this, we can wrap each instance into a separate struct, so each instance will have a separate @State:
I used generics here for view input <T: View> so we can easily switch from Image to some concrete View and so replace the back-engine.