Rank: Administration
Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor Joined: 23/11/2008(UTC) Posts: 523
|
Xamarin Forms - How to spin a visual element
Code:public async Task Spin(VisualElement element)
{
if (element != null)
{
await StartSpinTimer(new CancellationTokenSource(), element); if (animateTimerCancellationTokenSource != null)
{
animateTimerCancellationTokenSource.Cancel();
animateTimerCancellationTokenSource.Dispose();
animateTimerCancellationTokenSource = null;
}
await element.RotateTo(0, 0); // reset to initial position
}
} private async Task StartSpinTimer(CancellationTokenSource tokenSource, VisualElement element)
{
try
{
//maintain a reference to the token so we can cancel when needed
animateTimerCancellationTokenSource = tokenSource; int idleTime = 10; //ms
await Task.Delay(TimeSpan.FromMilliseconds(idleTime), tokenSource.Token); //Do something here
Device.BeginInvokeOnMainThread(async () =>
{
await element.RelRotateTo(360, 800, Easing.Linear);
if (IsSpinning)
{
//Do this if you want to have it possibly happen again
await StartSpinTimer(new CancellationTokenSource(), element);
}
});
}
catch (TaskCanceledException ex)
{
//if we cancel/reset, this catch block gets called
Debug.WriteLine(ex);
}
// if we reach here, this timer has stopped
}
Here we use a button for example. The button can be referenced via Command Interface in one of the following two ways. 1. Code:<views:CustomImageButton x:Name="buttonToSpin" Source="{Binding TheIcon}"
Command="{Binding TheCommand}"
CommandParameter="{x:Reference buttonToSpin}"/>
2. Code:<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TheCommand}" CommandParameter="{x:Reference buttonToSpin}" />
</StackLayout.GestureRecognizers>
CommandParameter has a reference to buttonToSpin. It is the visual element in the example code above which will be rotated through RelRotateTo.
Edited by user Monday, 21 October 2019 5:42:39 PM(UTC)
| Reason: Not specified
|