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

eBook
€8.99 €27.99
Paperback
€34.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Colour book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Colour book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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
€18.99 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
€189.99 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 €5 each
Feature tick icon Exclusive print discounts
€264.99 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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 95.97
Elevate SwiftUI Skills by Building Projects
€26.99
SwiftUI Cookbook
€33.99
Animating SwiftUI Applications
€34.99
Total 95.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela