Xamarin.Forms
has multiple functions for animating views. We have access to the following functions:
FadeTo
: This is used to animate opacity (that is, fade in/out).RotateTo
: This is used to animate rotations.ScaleTo
: This is used to animate size.TranslateTo
: This is used to animate (x, y) positions.LayoutTo
: This is used to animate x, y, width, and height.Stay away from the LayoutTo
function. Jason Smith (the creator of Xamarin.Forms
) recommends you stick with the TranslateTo
instead. The issue with LayoutTo
is the parent of the view you are calling LayoutTo
on will not be aware of the translation/resize that happened and will simply overwrite it at the next layout cycle (like when you rotate the device). This is because LayoutTo
is calling the same method Layouts call to position children.
We are now going to use a few of these animation functions to animate our target image when a use touches to focus. The AnimateFocalTarget
function will be responsible for performing the animations every time a user touches the view. At first, it will change the tint color of the image to green, then translate the (x, y) coordinate to the starting position, expand the scale, fade the image, contract the scale, and wait a second until the tint color changes back to white:
#region Private Methods private async Task AnimateFocalTarget(Point touchPoint) { _focalTarget.TintColorString = "#007F00"; await _focalTarget.TranslateTo(touchPoint.X - (IMG_TARGET_BOUND / 2), touchPoint.Y - (IMG_TARGET_BOUND / 2), 0).ConfigureAwait(false); await _focalTarget.ScaleTo(1, 0); // fade in await _focalTarget.FadeTo(0.7f, 25); await _focalTarget.ScaleTo(0.5, 250); _focalTarget.TintOn = true; await Task.Delay(1000); _focalTarget.TintColorString = "#FFFFFF"; _isAnimating = false; } #endregion
All these await functions, is there a cleaner way?
In a lot of cases, you will need to combine multiple transitions at any one time. Let's replace the preceding combination of animations with a compound animation.
3.135.249.220