Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Animating SwiftUI Applications
Animating SwiftUI Applications

Animating SwiftUI Applications: Create visually stunning and engaging animations for iOS with SwiftUI

Arrow left icon
Profile Icon Stephen DeStefano 
Arrow right icon
₹800 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (12 Ratings)
Paperback Mar 2023 478 pages 1st Edition
eBook
₹799 ₹2740.99
Paperback
₹3425.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Stephen DeStefano 
Arrow right icon
₹800 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9 (12 Ratings)
Paperback Mar 2023 478 pages 1st Edition
eBook
₹799 ₹2740.99
Paperback
₹3425.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799 ₹2740.99
Paperback
₹3425.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Animating SwiftUI Applications

Understanding Animation with SwiftUI

In the first chapter, we covered many SwiftUI fundamentals we will see when we start building projects. In this chapter, we will look at how animations work, including timing curves and animatable properties, which will lay the foundation for the projects we build.

The following are the key topics we will explore:

  • What is animation?
  • Understanding timing curves
  • Understanding animation types
  • Triggering animations
  • Exploring animatable properties

Technical requirements

You can find the code for this chapter on GitHub in the Chapter 2 folder: https://github.com/PacktPublishing/Animating-SwiftUI-Applications.

What is animation?

Let’s consider the book’s definition of animation. Animation is a series of static images displayed in rapid succession to create the illusion of motion. The images, or frames, are usually displayed at a rate of 24 or 30 frames per second from the beginning to the end, which is fast enough to create the illusion of continuous motion. These can be created using a variety of techniques, including hand-drawn, computer-generated, and stop-motion animations.

Looking at this definition, we can see that there is a start point and an end point to animation, and the images in between are all slightly different; when played, our eyes cannot pick out the individual images, which means we perceive movement or animation.

In SwiftUI, we have to define the start point (where the animation begins) and the end point (where the animation ends). However, when we code, we don’t actually put a bunch of still images between both end points (though we can); what we usually do is use a single image and then animate the properties of that image, such as its location on the screen, its opacity, or its color.

In addition to images, we can also animate RGB colors by changing their hue or the corner radius of shapes, and if we draw a shape, we can animate the individual lines (paths) or the strokes around it.

It works like this: if we want a rectangle to move from the bottom left to the top right of the iPhone or iPad screen, we declare it in code (that declarative syntax thing again) by using the animation modifier. Then SwiftUI does the magic for us, moving the object, or in SwiftUI speak, “transitioning” the object from a start point to an end point, filling in all the gaps along the way with whatever values we are working with (integers, colors, opacity, etc.). The process of going through all the values to create a smooth fluid motion is called interpolation.

SwiftUI fills in those gaps for us really well, but it cannot animate every property of every view. Only properties considered “animatable” can be animated; things such as a view’s color, opacity, rotation, size, position, corner radius, and strokes. Nearly all properties that have a numerical value are animatable.

SwiftUI includes basic animations with default or custom easing or timing curves (a timing curve refers to the speed at the start and end of the animation), as well as spring animations. Spring animations have a bouncy effect to them and can be adjusted from a slight bounce to a very pronounced bounce, similar to a rubber ball bouncing on the floor.

You can also change many customization options, such as the speed of an animation, add a “wait” time before the animation starts, and have an animation repeat itself.

Let’s continue by diving deeper into animation timing curves, seeing what they look like and how they affect an animation.

Understanding timing curves

Animations have what are called curves. A curve, or more specifically, a timing curve, refers to the speed at which the animation starts and how it should end.

SwiftUI provides several timing curves to choose from that we can use inside the animation modifier. It’s called a timing curve because if you were to plot each point of the animation’s movement from start to finish on a graph, and draw a line by connecting those points, most of them would create a curved line, as in this illustration:

Figure 2.1: The ease timing curves

Figure 2.1: The ease timing curves

This graph shows three animation timing curves: easeIn, easeOut, and easeInOut. The beginning of the animation is at the bottom left, and the end is at the top right. In the easeInOut timing curve, the animation starts slow, speeds up, and then finally slows down before coming to a complete stop.

There is also a linear timing curve. An animation using this curve will have the same rate of speed at its beginning as it does at its end. If you were to plot it on a graph, it would be a straight line, like so:

Figure 2.2: The linear timing curve

Figure 2.2: The linear timing curve

Timing curves are not complicated – we get to choose the ones we want based on how we want the animation to look and perform. If you don’t specify a timing curve, you will get the default curve, the easeInOut one. We will use some of these SwiftUI-provided timing curves in our projects.

In the next section, I want to explain the two distinct types of animation in SWiftUI: implicit and explicit.

Understanding animation types

There are two types of animations in SwiftUI: implicit and explicit. Let’s look at what these animation types do and the difference between the two.

An implicit animation is an animation that is automatically applied to a property when its value is changed. In SwiftUI, implicit animations are created using the .animation modifier. Here is an example:

struct ContentView: View {
    @State private var grow: CGFloat = 1
    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.blue)
            .onTapGesture {
                self.grow += 0.5
            }
            .scaleEffect(grow)
            .animation(.default, value: grow)
    }
}

In this example, we use a tap gesture to scale up the size of a circle; when tapped, the circle will grow by half its size. The .animation modifier uses the default animation style, which will animate the circle using an easeInOut timing curve by default.

You can also use other animation styles. For example, here, I added a spring style instead of the default style:

var body: some View {
        Circle()
••••••••
            .scaleEffect(grow)
            .animation(.spring(dampingFraction: 0.3,blendDuration: 0.5),value: grow)
    }

This style will animate the circle and add a springy effect to it.

So implicit animations are a convenient way to add basic animations to your SwiftUI app without having to write any explicit animation code. The animations are applied using the animation modifier.

Sometimes though, you may want more from your animation, and implicit animations may not give you the degree of control that you are looking for. In this case, you can use explicit animations instead.

An explicit animation is an animation you create and add inside the code block using the withAnimation function. Here’s an example:

struct ContentView: View {
    @State private var scaleUp: CGFloat = 1
    var body: some View {
        Button(action: {
            //Animate the scale of the view when the button is               tapped
            withAnimation(.interpolatingSpring(stiffness: 60,               damping: 2)) {
                scaleUp *= 1.4
            }
        }) {
            Text("Scale up")
                .scaleEffect(scaleUp)  // explicit animation
        }
    }
}

In this example, tapping the button will animate the scale of the text using a spring animation. The duration of the animation will be determined by the system’s default animation settings, but the curve of the animation will be customized using the interpolatingSpring function.

Additionally, you can customize the duration of the animation by specifying a duration parameter in the interpolatingSpring function. The following is an example of this:

withAnimation(.interpolatingSpring(stiffness: 60, damping: 2, duration: 2.5)) { scaleUp *= 1.5 }

This will cause the animation to last for 2.5 seconds.

So, the difference when using explicit animations versus implicit animations is that they can give you more control over the details of the animation, or when you want to animate multiple properties simultaneously; you can put as much code into the withAnimation block as needed. However, they can be more work to set up than implicit animations.

You can also have the animation repeat itself a pre-set number of times or indefinitely. Here’s an example of repeating the previous animation forever and auto-reversing it:

withAnimation(.interpolatingSpring(stiffness: 60, damping: 2).repeatForever(autoreverses: true)) {
                    scaleUp *= 1.4
                }

In the previous example, I altered the code in the withAnimation function to include the repeatForever option and set the autoreverses parameter to true. When you run the code, the text will scale up with a springy effect, and when it’s done bouncing (about 3 seconds or so), the animation will start over, repeating endlessly or until the app is stopped.

Those are the two types of animations; next is a list of ways to trigger animations.

Triggering animations

So, how do we trigger animations? There are several ways to do so in SwiftUI, including using the following SwiftUI modifiers, methods, and functions:

  • The .animation() modifier: This modifier allows you to specify the type of animation used when a view appears or disappears or when its state changes.
  • The withAnimation() function: This function allows you to wrap a block of code that changes the state of a view, and it will automatically animate the changes.
  • A gesture: This is a way to interact with a view by performing actions such as tapping, dragging, or pinching. You can use a gesture to trigger an animation when a certain action is performed on a view.
  • A timer: This allows you to specify an animation to be performed over a certain period of time. You can use a timer to animate the changes to a view’s state over a specific duration.
  • The onAppear() and onDisappear() modifiers: These modifiers allow you to specify code to be executed when a view appears or disappears. These modifiers can trigger an animation when a view appears or disappears.
  • Button and other control views: A button, slider, picker, or other control type view in SwiftUI can be a trigger for an animation.

There are other ways to trigger animations, but these are the main ones that we will cover here. Whatever you choose will depend on the specific needs of your app and the behavior you want to produce. We will explore these different triggers when we start building our projects in the coming chapters.

Let’s continue by looking at various properties that can be animated in SwiftUI.

Exploring animatable properties

In this section, we will explore some of the animatable properties. Here is a list of the ones that we will look at:

  • Offset
  • Hue rotation
  • Opacity
  • Scale
  • Stroke
  • Trim
  • Corner radius

Let’s take a look at them in more detail.

The offset property

The first property we will look at that is animatable is the offset property. This property is responsible for offsetting a view on the x- and y-axes, basically giving you control to place that view anywhere on the screen. The following is an example of animating the offset modifier that has been placed on a rectangle shape:

struct Offset_Example: View {
    @State private var moveRight = false
    var body: some View {
       //MARK: - ANIMATE OFFSET
        VStack {
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(.blue)
                .frame(width: 75, height: 75)
                .offset(x: moveRight ? 150 : 0, y: 350 )
                .animation(Animation.default, value: moveRight)
            Spacer()
            Button("Animate") {
                moveRight.toggle()
            }.font(.title2)
        }
    }
}

After you put that code into your ContentView file, your preview will look like Figure 2.3. When you press the Animate button, the blue rectangle will move to the right, and when you press it again, it will return to its original starting position.

Figure 2.3: Animating the offset

Figure 2.3: Animating the offset

This is how the code works. When the Animate button is pressed, the moveRight variable has its value toggled or changed to true, and the offset modifier has a ternary operator in there for its x parameter.

A ternary operator is an operator that accepts a Boolean variable and checks to see whether it’s true or false. If the variable is true, the value to the left of the colon is used, but if the variable is false, the value to the right of the colon is used. This makes it similar to an if statement but different because an if statement can check for multiple conditions.

So, if moveRight is true, then the rounded rectangle is placed 150 points to the right; otherwise, if false, it is left where it is (the 0 value means do nothing). The animation modifier also picks up on any change because it has the moveRight variable in there for the value parameter. This value parameter takes the variable that you are using for the animation. The animation modifier will then interpolate over the values from the start to the finish point and move the object smoothly, creating a nice, fluid animation.

Here’s a way to really see how the animation modifier is working. If you comment out the animation statement in the code and press the button, you will see that the object still moves 150 points to the right, but it does so instantly; there is no gliding across the screen now; the object just appears at its new location 150 points to the right. To create smooth, fluid animations, we need that animation modifier and its behind-the-scenes interpolating magic. This is part of the reason why we use less code in SwiftUI versus coding animation in UIKit; much of the heavy lifting is already done for us in the background with SwiftUI.

This was an example of animating an object from one point to another by changing the numerical value for the x parameter in the offset modifier. Let’s look at another property that’s animatable: HueRotation.

Hue rotation

Hue rotation is a type of color effect that can be applied to views and other components. It’s a modifier that allows you to adjust the hue of a color by adding or subtracting a fixed angle from its hue value. You can use hue rotation to create a range of related colors.

The modifier has an angle parameter that takes a value in radians or degrees. That value is based on a circle, which is 360 degrees and represents a wheel of all the colors that we can think of.

Let’s look at an Xcode example:

struct Hue_Rotation_Example: View {
    @State private var hueRotate = false
        var body: some View {
        //MARK: - ANIMATE HUE ROTATION
        VStack(spacing: 20) {
            Text("ANIMATE HUE ").font(.title2).bold()
            // rotate the colors and stop halfway around the               color wheel
            RoundedRectangle(cornerRadius: 25)
                .frame(width: 200, height: 200)
                .foregroundColor(.red)
                .hueRotation(Angle.degrees(hueRotate ? 180 :                   0))
                .animation(.easeInOut(duration: 2), value:                   hueRotate)
            // rotate the colors around the color wheel one               full revolution (360 degrees)
            Divider().background(Color.black)
            Text("ANIMATE HUE WITH GRADIENT").font(.title2).              bold()
            AngularGradient(gradient: Gradient(colors: [Color.              red, Color.blue]), center: .center)
                .hueRotation(Angle.degrees(hueRotate ? 360 :                   0))
                .animation(.easeInOut(duration: 2), value:                   hueRotate)
                .mask(Circle())
                .frame(width: 200, height: 200)
            Button("Animate") {
                hueRotate.toggle()
            }
            .font(.title)
        }
    }
}

When you add the code into Xcode, your previews will look like Figure 2.4:

Figure 2.4: Animating the hue rotation

Figure 2.4: Animating the hue rotation

I created two objects in this example: a rounded rectangle and an angular gradient circle.

In the rounded rectangle, I used a ternary operator to check whether the hueRotate variable is true. When it becomes true via the Animate button being pressed, the value to the left of the colon inside the ternary operator is used, 180 degrees. Then the animation starts going through the color spectrum and stops halfway through to display that color.

Notice the use of the duration function just after the timing curve. This function allows us to set the duration of the animation; do we want it to happen fast, or do we want the animation to happen over a longer period? It has one parameter, and that is the amount of time we want the animation to take to complete; for that, we use an integer value. I set the value to 2, so it can slow things down a little, taking the animation 2 seconds to complete.

Looking at the angular gradient example, I’m using a value of 360 degrees. When we press the Animate button, the code animates through the entire color wheel and stops where it started (360 degrees is one revolution of a circle), thus displaying the original color.

Taking a look at the hueRotate variable inside the body of the button, we have two ways that we can start the animation. The first is by explicitly setting hueRotate to true, like this:

hueRotate = true

Or by using the toggle method like we’re doing in the code:

hueRotate.toggle()

The difference between these two ways of starting the animation is that firstly, the animation starts and then finishes, but it never reverses itself with subsequent button presses. If you’d like the animation to start and finish, and on the next button press reverse itself, then use the toggle method.

What’s also very interesting is that we can animate the colors of shapes and other objects, but also animate the colors that make up images, as we will see in the upcoming projects.

You can also use the hueRotation() modifier in combination with other modifiers, such as brightness() or saturation(), to create some complex and interesting color adjustments.

Let’s continue looking at the different properties to animate and at a very common property, opacity.

Opacity

Opacity refers to the transparency of a view, whether you can see it clearly, whether it is partially visible, or maybe you can’t see it at all. We can use the opacity modifier to make views appear and disappear. When we add animation to the opacity, the transition from shown to hidden is interpolated over, so it smoothly fades in and out.

Here's an example of adding opacity to an animation:

struct Opacity__Example: View {
    @State private var appear = true
    var body: some View {
//MARK: - ANIMATE OPACITY
        VStack{
            Text("Appear/Disappear")
                .font(.title).bold()
            Circle()
                .foregroundColor(.purple)
                .opacity(appear ? 1 : 0)
                .animation(.easeIn, value: appear)
                .frame(height: 175)
            Button("Animate") {
                appear.toggle()
            }.font(.title2)
            //MARK: - OVERLAPPING OPACITY
            VStack{
                Text("Overlapping Opacity").bold()
                    .font(.title)
                Circle()
                    .foregroundColor(.yellow)
                    .frame(height: 100)
                    .opacity(0.5)
                Circle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .opacity(0.5)
                    .padding(-60)
            }.padding(60)
        }
    }
}

The preceding code will produce the following results, as shown in Figure 2.5:

Figure 2.5: Animating the opacity

Figure 2.5: Animating the opacity

In our first example, the animation variable is called appear, and it’s set to true as its default value, which shows the circle. When the Animate button is pressed, the variable gets toggled to false, and the circle animates itself until it completely disappears. And when the button is pressed again, the animation gets set to true, and the circle becomes visible again. Again, using the animation modifier initiates the interpolation over the start and end values, so the circle doesn’t just appear or disappear instantly; there is a gradual change of state until the end of the animation is reached.

The second example of the two circles overlapping at the bottom of the screen demonstrates a unique component of opacity in SwiftUI. When we apply the opacity modifier to a view that already had its opacity transformed, the modifier will multiply the overall effect. For example, the yellow and red circles have their opacity set at 50%, overlapping each other. The top red circle allows some of the bottom yellow circle to show through, thus multiplying the opacity effect so that area is a little darker, and at the same time, mingling the two colors, creating orange.

Next, let’s take a look at animating the size or scale of a view, which we can do with the scaleEffect modifier.

Scale

Every view has a specific size, and we can change that size by scaling it up or down with animation. We can do this with the scaleEffect modifier. Here’s an example of how we can animate the scale of a view:

struct Scale_Example_One: View {
    @State private var scaleCircle = false
    var body: some View {
            //MARK: - ANIMATE THE SCALE OF A CIRCLE SHAPE
            VStack {
                Text("SCALE SHAPE").font(.title).bold()
                Circle()
                    .frame(width: 150)
                    .foregroundColor(.green)
                    .scaleEffect(scaleCircle ? 0.1 : 1)
                    .animation(.default, value: scaleCircle)
                Button("Scale Shape") {
                    scaleCircle.toggle()
                }
            }.font(.title2)
        }
    }

The preceding code will produce the following results, as shown in Figure 2.6:

Figure 2.6: Scaling a shape

Figure 2.6: Scaling a shape

You should be starting to recognize much of the code that we’re using; for example, we use a VStack to hold our views, so they get stacked vertically, and we can use the button control as a way to start the animation.

In the example, I’m creating a simple green circle and using the scaleEffect modifier, passing in our animating variable. When the state changes to true, the circle scales down to one-tenth of its size, and when false, it goes back to its original size.

We’re using the animation modifier again with the default timing curve. The default curve is an easeInOut curve, which we discussed earlier in the chapter. An easeInOut curve will cause the animation to start slowly, then ramp up to its top speed, and then finish by easing out slowly again.

Let’s look at another example of scaling up and down, but instead of scaling a shape that we created using the circle initializer, we’re using a system image to show you that you can also scale images:

struct Scale_Example_Two: View {
    @State private var scaleBug = false
    var body: some View {
        //MARK: - ANIMATE THE SCALE OF A SYSTEM IMAGE
        VStack{
            Text("SCALE IMAGE").font(.title).bold()
            Image(systemName: "ladybug.fill")
                .renderingMode(.original) //allows multicolor                   for SF Symbols
                .resizable()
                .frame(width: 150, height: 150, alignment:                   .center)
                .scaleEffect(scaleBug ? 0.1 : 1)
                .animation(.default, value: scaleBug)
                .padding(10)
            Button("Scale Image") {
                scaleBug.toggle()
            }
        }.font(.title2)
    }
}

The preceding code will produce the following results, as shown in Figure 2.7:

Figure 2.7: Scaling an image

Figure 2.7: Scaling an image

This particular image is a system image from the SF Symbols app. If you don’t have this app yet, I highly recommend it. You can download it for free at the Apple Developer portal. In it, Apple has given us thousands of images we can use in our code. And what’s new in the latest release is that now, many of the images can be rendered in multicolor: we have to set the rendering mode to .original so the image gets shown with colors, instead of just black or white.

Note

Not all images can be colored. Look in the SF Symbols app to see which ones can be colored.

Finally, in this third example of a scaling animation, we use the anchor method, which scales the view by the given amount in both the horizontal and vertical directions relative to an anchor point:

struct Scale_Example_Three: View {
    @State private var scaleFromAnchor = true
    var body: some View {
                VStack{
            Text("SCALE FROM ANCHOR ").font(.title).bold()
            Image(systemName: "heart.fill")
                .renderingMode(.original) //allows the use of                   multicolor for SF Symbols
                .resizable()
                .frame(width: 150, height: 125, alignment:                   .center)
                .scaleEffect(scaleFromAnchor ? 1 : 0.2, anchor:                   .bottomTrailing)
                .animation(.default, value: scaleFromAnchor)
                .padding(10)
            Button("Scale from Anchor") {
                scaleFromAnchor.toggle()
            }
        }.font(.title2)
    }
}

The preceding code will produce the following results, as shown in Figure 2.8:

Figure 2.8: Scaling from an anchor point

Figure 2.8: Scaling from an anchor point

All views have an anchor point, which is usually in the middle of the view. But we can change that anchor point, and have the animation scale the object based on where that anchor point is. In the code, I used the .bottomTrailing option as the anchor point, so when we press the button, the heart image scales down and toward the trailing edge (the right side of the screen), rather than scaling from the center of the object. However, SwiftUI also gives us the following anchor points to choose from:

  • bottomTrailing
  • trailing
  • bottom
  • center
  • top
  • bottomLeading
  • topLeading
  • topTrailing
  • leading

In this final section, we will look at three more properties that can be animated: stroke, trim, and cornerRadius.

Stroke, trim, and corner radius

Let’s now look at three more properties we can animate: the stroke of a line, the trim of a circle, and the corner radius of a rectangle.

The stroke of a shape is the outline or border of the shape. It has a particular color and width and can have various attributes such as line cap style or line join style. Let’s animate the stroke of a rectangle, so it gets thicker or thinner with each button press:

struct Stroke_Example: View {
    @State private var animateStroke = false
    var body: some View {
        //MARK: - ANIMATE THE STROKE OF THE ROUNDED RECT
        VStack{
            Text("ANIMATE STROKE").font(.title).bold()
            RoundedRectangle(cornerRadius: 30)
                .stroke(Color.purple, style:                   StrokeStyle(inewidth: animateStroke ? 25 :                   1))
                .frame(width: 100, height: 100)
                .animation(.default, value: animateStroke)
            Button("Animate Stroke") {
                animateStroke.toggle()
            }
        }.font(.title2)
    }
}

Either a thick or thin stroke line is created around the rectangle, as shown in Figure 2.9:

Figure 2.9: Animating the stroke

Figure 2.9: Animating the stroke

The first thing we do is define our animation variable, setting its initial value to false. Looking inside the stroke modifier, I pass the animateStroke variable as an argument to the line width parameter, so when it does become true, it changes stroke to 25 points (otherwise, it will be 1 point). Again, we also use the default timing curve inside the animation modifier, and when we run this, stroke is smoothly modified from a thickness of 25 points, then back to 1 point when the button is pressed again.

Here is another example where we are using the trim modifier this time:

struct Trim_Example: View {
    @State private var animateTrim = false
    @State private var circleTrim: CGFloat = 1.0
    
    var body: some View {
        //MARK: - ANIMATE THE TRIM MODIFIER OF A CIRCLE
        VStack {
            Text("ANIMATE TRIM").font(.title).bold()
                .padding(.top, 10)
            Circle()
                .trim(from: 0, to: circleTrim)
                .stroke(Color.red, style: StrokeStyle(inewidth:                   30, lineCap: CGLineCap.round))
                .frame(height: 150)
                .rotationEffect(.degrees(180))
                .animation(.default, value: animateTrim)
                .padding(.bottom, 20)
            Button("Animate Trim") {
                animateTrim.toggle()
                circleTrim = animateTrim ? 0.25 : 1
            }
        }.font(.title2)
    }
}

The trim modifier takes two parameters: from (meaning what part of the circle we want to start trimming from) and to (meaning where we want to end the trimming). The from parameter is set to 0, which means there will be a complete circle on the screen as we are not trimming yet. The code produces the following results, a circle that has its line trimmed off and restored when the button is pressed, as shown in Figure 2.10:

Figure 2.10: Animating the trim

Figure 2.10: Animating the trim

Also, notice we use two @State variables to work with the trim modifier, one called animateTrim, to trigger the animation, and one called circleTrim, which is a numerical value of the CGFloat type. This variable will hold the amount of circle we want to trim off. Initially, it gets set to 1, so the whole circle is visible.

Note

A CGFloat type is a floating-point number. CG stands for Core Graphics, which is an older coding paradigm was used in Apple’s graphic framework, but is still used in SwiftUI.

Looking inside the button code, then within the circleTrim variable, we’re storing one of two values using the ternary operator: either .25, or 1. This means that when animateTrim toggles to true, the code trims off 75% of the circle and leaves 25%; when animateTrim toggles to false, the value of 1 is used, which represents 100% of the circle. So, the values in the ternary operator represent how much of the circle to keep.

If we run the code, we see we have a nice trimming animation of this circle. The line of code called CGLineCap.round refers to the shape of the line that’s drawn at the end points, and it can be round, square, or butt line cap.

And just to have a little fun here, if we go into the trim modifier and change the from parameter to 0.5 instead of 0, we now start the drawing halfway through the circle. Run the code, and it looks like we’re animating or painting a smile and then removing the smile when we press the button again.

Note

If this code seems a bit confusing, where you see the trim modifier being set for the circle, and the circleTrim variable being set in the button body, then think of the trim modifier as the “where” part of the trimming. This means where do we want to start and end the trimming? Then, think of the ternary operator inside the button as the “how much,” meaning how much do we want to trim off the circle and how much of it do we want to keep?

Let’s now move on to the final example. In this example, we will take a look at how you can animate the corner radius of a rectangle. The corner radius refers to how sharp you want to make the corners of a rectangle; you can go all the way from a 90° angle up to a much higher value to create a smooth, rounded corner.

All the code is similar to what we’ve used so far except for the use of the cornerRadius modifier. The following is an example of the code:

struct Corner_Radius_Example: View {
    @State private var animateCornerRadius = false
    
    var body: some View {
        //MARK: - ANIMATE THE CORNER RADIUS
        VStack{
            Text("ANIMATE CORNER RADIUS").font(.title).bold()
                .padding(.top, 30)
            Rectangle()
                .foregroundColor(.green)
                .frame(width: 150, height: 150)
            .cornerRadius(animateCornerRadius ? 0 : 75)
            .animation(.default, value: animateCornerRadius)
            .padding(.bottom, 20)
            Button("Animate Corner Radius") {
                animateCornerRadius.toggle()
            }
        }.font(.title2)
    }
}

This code produces the following results: a rectangle with its corner radius changed from a 90° angle all the way up to create a circle. So, we’re changing a rectangle into a circle and back again when the button is pressed, as shown in Figure 2.11:

Figure 2.11: Animating the corner radius

Figure 2.11: Animating the corner radius

In the code, the line that’s doing most of the work is this one:

.cornerRadius(animateCornerRadius ? 0 : 75) 

The animateCornerRadius variable gets passed into the cornerRadius modifier, which then gets checked for the true or false values; if it is false, it gets a value of 75 placed into it, which will make the size of this rectangle animate into a perfectly round circle. And when toggled back to true, the circle animates into a rectangle with 90-degree corners by having its corner radius changed to 0.

Note that the reason why the code creates a perfect circle is that we set the frame of the rectangle’s width and height to 150 points, thus creating a square, and anytime you set a corner radius to half the width or height of a square, you will always get a perfect circle.

SwiftUI gives us more ways to animate objects in addition to these, and we will explore them in the coming chapters when we start building projects.

Summary

In this chapter, we looked at how animations work, the two types of animation in SwiftUI, implicit and explicit, and many of the properties that can be animated. These include hue rotation, opacity, a view’s position on the screen and size, stroke, trim, corner radius, and timing curves.

This was an important step needed to guide you along on your SwiftUI animations adventure. Remember, if a property is a numerical value, it almost always can have an animation applied to it.

In the next chapter, we will start working on some projects. For our first project, we will create an app similar to Apple’s breathing app (very popular on Apple watches) and learn how to combine more than one animation in a view.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the basics of declarative programming and animation
  • Understand the fundamentals of SwiftUI and animatable properties
  • Learn while working on beginner-to-advanced level animation projects

Description

Swift and SwiftUI are the backbone of Apple application development, making them a crucial skill set to learn. Animating SwiftUI Applications focuses on the creation of stunning animations, making you proficient in this declarative language and employing a minimal code approach. In this book, you'll start by exploring the fundamentals of SwiftUI and animation, before jumping into various projects that will cement these skills in practice. You will explore some simple projects, like animating circles, creating color spectrums with hueRotation, animating individual parts of an image, as well as combining multiple views together to produce dynamic creations. The book will then transition into more advanced animation projects that employ the GeometryReader, which helps align your animations across different devices, as well as creating word and color games. Finally, you will learn how to integrate the SpriteKit framework into our SwiftUI code to create scenes with wind, fire, rain, and or snow scene, along with adding physics, gravity, collisions, and particle emitters to your animations. By the end of this book, you’ll have created a number of different animation projects, and will have gained a deep understanding of SwiftUI that can be used for your own creations.

Who is this book for?

This book is for aspiring SwiftUI developers who have a basic understanding of Swift. It can also be used by SwiftUI developers, UIKit developers, and iOS developers that are new to SwiftUI and want to improve their animation proficiency.

What you will learn

  • Understand the fundamentals of SwiftUI and declarative programming
  • Master animation concepts like state variables and time curves
  • Explore animation properties like hueRotation, opacity, and scale
  • Create animations using physics, gravity, collision, and more
  • Use the GeometryReader to align views across various platformsCombine different animations for more dynamic effects
  • Add audio to your animations for an interactive experience

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 13, 2023
Length: 478 pages
Edition : 1st
Language : English
ISBN-13 : 9781803232669
Vendor :
Apple
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 13, 2023
Length: 478 pages
Edition : 1st
Language : English
ISBN-13 : 9781803232669
Vendor :
Apple
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,384.97
Elevate SwiftUI Skills by Building Projects
₹2606.99
SwiftUI Cookbook
₹3351.99
Animating SwiftUI Applications
₹3425.99
Total 9,384.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Chapter 1: Exploring the Fundamentals of SwiftUI Chevron down icon Chevron up icon
Chapter 2: Understanding Animation with SwiftUI Chevron down icon Chevron up icon
Chapter 3: Creating a Breathing App Chevron down icon Chevron up icon
Chapter 4: Building a Record Player Chevron down icon Chevron up icon
Chapter 5: Animating Colorful Kaleidoscope Effects Chevron down icon Chevron up icon
Chapter 6: Animating a Girl on a Swing Chevron down icon Chevron up icon
Chapter 7: Building a Series of Belts and Gears Chevron down icon Chevron up icon
Chapter 8: Animating a Bouquet of Flowers Chevron down icon Chevron up icon
Chapter 9: Animating Strokes around Shapes Chevron down icon Chevron up icon
Chapter 10: Creating an Ocean Scene Chevron down icon Chevron up icon
Chapter 11: Animating an Elevator Chevron down icon Chevron up icon
Chapter 12: Creating a Word Game (Part 1) Chevron down icon Chevron up icon
Chapter 13: Creating a Word Game (Part 2) Chevron down icon Chevron up icon
Chapter 14: Creating a Color Game Chevron down icon Chevron up icon
Chapter 15: Integrating SpriteKit into Your SwiftUI Projects Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.9
(12 Ratings)
5 star 91.7%
4 star 8.3%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nirav May 18, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Animating SwiftUI Applications: Create visually stunning and engaging animations for iOS with SwiftUI" is a remarkable book that caters to both beginners and experts in SwiftUI animation. With its clear and concise explanations, practical examples, and insightful tips, this book stands out as an invaluable resource for anyone interested in creating captivating animations for iOS applications.One of the book's standout features is its accessibility to beginners. The authors have done an excellent job of breaking down complex concepts and techniques into easily understandable chunks. They start with the basics, gradually building upon the reader's knowledge, and eventually, delve into more advanced animation techniques. Whether you are new to SwiftUI or have some prior experience, the book offers a gentle learning curve that ensures a solid foundation in animation principles.
Amazon Verified review Amazon
Oleksandr Piskun Apr 09, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is very well written. I have been working with SwiftUI for less than a year, and this book helps me understand better concepts, using suitable examples.The book is well-structured and organized.I would recommend it for both beginners and experienced iOS developers.
Amazon Verified review Amazon
Justin Horner Mar 29, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Reading through this book and making the projects was a great time, and I recommend it even if you don't necessarily consider yourself a Swift / iOS developer.In fact, I believe this is much better introduction to SwiftUI than the path I took. The projects are interesting, and you'll take away some transferable general animation knowledge.It covers all the topics you'd expect, such as custom views, modifiers, previews, built-in views, timing, closures, layouts, etc.
Amazon Verified review Amazon
Krishna May 08, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Stephen's "Animating SwiftUI Applications" is an exceptional resource for iOS developers seeking to master animations in SwiftUI. The guide offers a comprehensive approach to the subject matter, and I have found it to be an invaluable tool for expanding my knowledge and skills in this domain. As an experienced iOS developer and reviewer, I must say that this book is an exceptional learning resource that comprehensively covers all the fundamental concepts pertaining to animations in SwiftUI.The book's exceptional quality lies in its aptitude to elucidate fundamental concepts and address queries that iOS developers may encounter while animating in SwiftUI. The author's writing exhibits a remarkable clarity and concision, rendering the content easily comprehensible and navigable for the readers. This comprehensive guide delves into a plethora of topics, ranging from basic animations such as "Breath Mindfulness" to intricate techniques, offering in-depth insights into every facet of animation in SwiftUI.The book's noteworthy attribute lies in its ability to cater to novice SwiftUI developers with ease. Developers with a minimum of 3-4 months of experience in SwiftUI can effortlessly comprehend the material and acquire the skills to design captivating animations. This book is a great resource for developers of all levels, from novices to seasoned professionals, seeking to enhance their animation expertise.I understand the initial hesitation one may have when considering the use of an ebook or other formats. It can be challenging to compare the results of your work with the content in the book. Initially, I had some apprehensions regarding the book's efficacy, but as I delved deeper into the material and implemented the concepts, my reservations were assuaged. I must say, the results I achieved were quite impressive, and I must admit that the ebook format did not impede my learning experience.Stephen's "Animating SwiftUI Applications" is an essential resource for those seeking to elevate their proficiency in SwiftUI animations and augment the user experience of their applications. This publication exhibits exceptional craftsmanship, comprehensiveness, and a wealth of valuable insights. As an experienced iOS developer, I would suggest that while digital copies of books are convenient, there is something to be said for the tactile experience of reading a physical book. Therefore, my personal preference would be for a hard copy of the book. I strongly endorse this book to all iOS developers, irrespective of their proficiency level with SwiftUI.
Amazon Verified review Amazon
Amazon Customer Apr 08, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As an iOS developer who is passionate about learning and working with SwiftUI, "Animating SwiftUI Applications" by Stephen DeStefano has been an ideal resource for understanding animations and creating impressive projects. This engaging and informative guide skillfully breaks down complex concepts like State variables and timing curves.Following a logical structure and step-by-step explanations, the author guided me through captivating projects such as a breathing app and a record player. As the complexity of projects increases, it was satisfying to see myself develop confidence in my animation proficiency.The book delves into essential SwiftUI controls and introduces advanced features like SpriteKit and Particle Emitters, offering a comprehensive understanding of the framework."Animating SwiftUI Applications" is a must-read for aspiring iOS developers focusing on SwiftUI. Its relatable tone, captivating style, and organized structure make it a valuable resource for those eager to enhance their skills in the field. I've thoroughly enjoyed reading and working through the book so far and eagerly anticipate completing the rest of it.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.