SwiftUI - How to make motion and stop animation of pictures or emojis | Apple iOS Xcode YouTube Seminar #14


Swift5.1.3 Xcode11.3.1 SwiftUI


- How to create anime motion made of emojis or pictures.
- Start and stop motion programatically
- UIImage.animatedImage() is the key


anime motion created by photo picture or emoji


* Here is the highlight of YouTube tutorial.

There are various ways of moving object visually on iPhone APP. Typically, the way changes depending on what kind of object it is.

Let me begin this with an example of text message.


Text("text message horizontally")
.transition(.move(edge: .leading))



Let's see how this code is used in ContentView.


struct ContentView: View {
@State var trigger = false

var body: some View {
VStack {
Button(action: {
withAnimation {
self.trigger.toggle()
}
}) {
Text("H-Move")
}

Spacer().frame(height: 50)

if trigger {
Text("text message horizontally")
Image("180")
.transition(.move(edge: .leading))
}
}.font(.title)
}
}



Please build this and confirm how the text move horizontally. Not only for text message but also emojis can be moved in this code.

Next, let me show you how to move pictures to make some animation. Before you try this, prepare some pictures moving a little by a little.

In this tutorial, I will use some trump cards to rotate in appearance. Their file names of photos are from 180.jpg to 187.jpg.

You can also move the picture with as same following code as the one I showed above.


Image("180").transition(.move(edge: .leading))



But, the more dynamic movement can be achieved with the combination of multiple pictures.


var images : [UIImage]! = [UIImage(named: "180")!, UIImage(named: "181")!, UIImage(named: "182")!, UIImage(named: "183")!, UIImage(named: "184")!, UIImage(named: "185")!, UIImage(named: "186")!, UIImage(named: "187")!]
let animationImage = UIImage.animatedImage(with: images, duration: 0.8)

struct startAnimation: UIViewRepresentable {

func makeUIView(context: Self.Context) -> UIView {
let myView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
let myImage = UIImageView(frame: CGRect(x: 20, y: 100, width: 360, height: 300))
myImage.contentMode = UIView.ContentMode.scaleAspectFill
myImage.image = animationImage
myView.addSubview(myImage)

return myView
}

func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<startAnimation>) {
print("updated!")
}
}



With the duration parameter of the function, animatedImage(), you can adjust the motion speed. Function updateUIView() seems to be not necessary. But, the protocol UIViewRepresentable requires it.

Try to change CGRect to place the animation in different locations.


To get the source code, check the comment of my YouTube

Back to Table List

2020年01月25日