Dynamic ExpressionAnimation with Composition API
I talked about KeyFrame animations in a previous article. Composition API also has another type of animation: Expression animation.
With this animation, we will not set keyframes, but a mathematical formula which will define our animation. For example “3 * x + 10”, where x is a parameter passed to the animation.
We can use all the standard operators: +, -, /, *,… also “?:” to make the connections. There is a link to the full list at the end of article.
I talked about parameters in the animation later. We can make the dynamic animation by changing these parameters. Composition API will then recalculate the animation with the new value.
To make it truly dynamic, I will update these settings with the tilt of the phone. Thus, we can move an item on the screen by playing with the tilt of the phone. The animation and the element are all made using composition API.
Draw me a square
I’ll start by drawing a simple red square. But with Composition API.
I’ll create here a visual on the main Grid. I get the visual of the grid, I ask his compositor. And with I create a Visual Sprite. On which I apply a red Brush. I then put the size at 100 and I positioned in the middle of the grid. After that, I’ll add in the layer of the grid.
I create an ExpressionAnimation. The somewhat complex formula calculates the offset x and y of the square. With as limit the edges of the screen. I put this in a Vector3, because that’s what the Offset of the visual property request.
After I create a propertyset. It’s a class that will store values. I insert the parameters and then I pass this propertyset to the animation as a parameter. Then I start the animation by specifying the animation will animate the Offset property
Well, it’s good, but now we must bind it to tilt
I request an instance of the Inclinometer, I put it in LandscapeFlipped like that he will “fix” the values sent (I find it more natural when the device is in portrait. Yes it’s weird) and finally I told him to call a method when it has a new value. In this method, I’m simply updating the parameters related to the tilt. Composition API takes care of the rest.
Again, I’ve done that to touch the subject. We could write hundreds no nice articles on Composition API
For more info on the animations : https://docs.microsoft.com/en-us/windows/uwp/graphics/composition-animation