Coder Social home page Coder Social logo

xamanimation's Introduction

Xamanimation - Animation Library for Xamarin.Forms

Xamanimation is a library designed for Xamarin.Forms that aims to facilitate the use of animations to developers. Very simple use from C# and XAML code.

Xamanimation

We can define animations in XAML to a visual element when loading through a Behavior, use a trigger in XAML to execute the animation or from C# code.

Available animations:

  • Color
  • FadeTo
  • Flip
  • Heart
  • Jump
  • Rotate
  • Scale
  • Shake
  • Translate
  • Turnstile

Installation

To install Xamanimation, run the following command in the Package Manager Console.

PM> Install-Package Xamanimation

Animations directly from XAML

One of the main advantages of the library is the possibility of using animations from XAML. We must use the following namespace:

xmlns:xamanimation="clr-namespace:Xamanimation;assembly=Xamanimation"

Let's animate a BoxView:

<BoxView
     x:Name="FadeBox"
     HeightRequest="120"
     WidthRequest="120"
     Color="Blue" />

we can define animations directly in XAML (as Application or Page Resources):

<xamanimation:FadeToAnimation
     x:Key="FadeToAnimation"
     Target="{x:Reference FadeBox}"
     Duration="2000"
     Opacity="0"/>

Using the namespace of xamanimation, we have access to the whole set of animations of the library. In all of them there are a number of common parameters such as:

  • Target: Indicate the visual element to which we will apply the animation.
  • Duration: Duration of the animation in milliseconds.

Depending on the animation type used, we will have more parameters to customize the specific animation. For example, in the case of Fade Animation we will have an Opacity property to set how we modify the opacity.

To launch the animation we have two options:

  • Trigger: Called BeginAnimation that allows us to launch an animation when a condition occurs.
  • Behavior: We have a Behavior called BeginAnimation that we can associate to a visual element so that indicating the desired animation, we can launch the same when the element load occurs.

Using the Clicked event of a button we can launch the previous animation using the trigger provided:

<Button 
     Text="Fade">
     <Button.Triggers>
          <EventTrigger Event="Clicked">
               <xamanimation:BeginAnimation
                    Animation="{StaticResource FadeToAnimation}" />
          </EventTrigger>
     </Button.Triggers>
</Button>

We also have the concept of Storyboard as a set of animations that we can execute over time:

<xamanimation:StoryBoard
     x:Key="StoryBoard"
     Target="{x:Reference StoryBoardBox}">
     <xamanimation:ScaleToAnimation  Scale="2"/>
     <xamanimation:ShakeAnimation />
</xamanimation:StoryBoard>

Using C#

In the same way that we can use the animations of the library from XAML, we can do it from C# code. We have an extension method called Animate that expects an instance of any of the available animations.

If we want to animate a BoxView called AnimationBox:

<BoxView
     x:Name="AnimationBox"
     HeightRequest="120"
     WidthRequest="120"
     Color="Blue" />

Access the element, use the Animate method with the desired animation:

AnimationBox.Animate(new HeartAnimation());

Take control of the animation

You can control the duration of the animation using the Duration property. In addition to the type of Easing to use. Now, new properties have also been added such as:

Delay Add a delay before play the animation.

Repeat Forever Now you can create infinite animations if you need it.

Triggers!

Triggers allow you to start animations declaratively in XAML based on events or property changes.

<Entry 
    FontSize="16" 
    BackgroundColor="LightGray">
    <Entry.Triggers>
        <Trigger TargetType="Entry" Property="IsFocused" Value="True">
            <Trigger.EnterActions>
                <xamanimation:AnimateDouble TargetProperty="Entry.FontSize" To="24"/>
                <xamanimation:AnimateColor TargetProperty="Entry.TextColor" To="Red"/>
                <xamanimation:AnimateColor TargetProperty="VisualElement.BackgroundColor" To="Yellow" Delay="1000"/>
                <xamanimation:AnimateDouble TargetProperty="VisualElement.Rotation" To="12" Duration="100"/>
            </Trigger.EnterActions>
            <Trigger.ExitActions>
                <xamanimation:AnimateDouble TargetProperty="{x:Static Entry.FontSizeProperty}" To="16"/>
                <xamanimation:AnimateColor TargetProperty="{x:Static Entry.TextColorProperty}" To="Black"/>
                <xamanimation:AnimateColor TargetProperty="{x:Static VisualElement.BackgroundColorProperty}" To="LightGray"/>
                <xamanimation:AnimateDouble TargetProperty="{x:Static VisualElement.RotationProperty}" To="0"/>
            </Trigger.ExitActions>
        </Trigger>
    </Entry.Triggers>
</Entry>

You can animate any property of type Int, Double, Color, Thickness or CornerRadius. Available options:

  • AnimateInt
  • AnimateColor
  • AnimateCornerRadius
  • AnimateDouble
  • AnimateThickness

Progress Animations

Sometimes you need to animate something based on a value that changes over time, for example as a a the result of a user interaction.

A common scenario is using a scroll. A parallax effect, etc.

<BoxView 
    BackgroundColor="Red"
    CornerRadius="24, 24, 0, 0">
    <VisualElement.Behaviors>
        <xamanimation:AnimateProgressColor
            TargetProperty="VisualElement.BackgroundColor"
            Progress="{Binding ScrollY, Source={x:Reference ScrollBehavior}}" 
            Minimum="0"
            Maximum="200"
            From="Black"
            To="Red"/>
        <xamanimation:AnimateProgressCornerRadius
            TargetProperty="BoxView.CornerRadius"
            Progress="{Binding ScrollY, Source={x:Reference ScrollBehavior}}" 
            Minimum="0"
            Maximum="200"
            From="24, 24, 0, 0"
            To="0,0,0,0"/>
    </VisualElement.Behaviors>
</BoxView>

Available options:

  • AnimateProgressInt
  • AnimateProgressColor
  • AnimateProgressCornerRadius
  • AnimateProgressDouble
  • AnimateProgressThickness

Transitions

Provides the animated transition behavior on controls when they first appear. You can use this on individual objects or on containers of objects. In the latter case, child elements will animate into view in sequence rather than all at the same time.

<FlexLayout 
     Wrap="Wrap"
	 Direction="Row"
	 JustifyContent="Start"
	 AlignItems="Start"
	 AlignContent="Start">
	 <FlexLayout.Behaviors>
	 <xamanimation:EntranceTransition
	      Duration="1000"/>
	 </FlexLayout.Behaviors>
</FlexLayout>

Feedback

Please use GitHub issues for questions or comments.

Copyright and license

Code released under the MIT license.

xamanimation's People

Contributors

dennisstromberg avatar jsuarezruiz avatar ysmoradi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xamanimation's Issues

UWP App with .NET Native Compilation enabled fails w/ FadeToAnimation

Only with .NET Native Compilation enabled, a UWP app that uses a FadeToAnimation storyboard on appearing on a grid fails when setting Opacity=0 at Duration=0:

        <xamanimation:StoryBoard x:Key="EntriesAnimation" Target="{x:Reference UserEntries}">
            <xamanimation:FadeToAnimation Opacity="0" Duration="0" />
            <xamanimation:FadeToAnimation Opacity="1" Duration="500" />
        </xamanimation:StoryBoard>

The above results in a crash. Note that the same technique (applying at Duration 0) works just fine with TranslateTo, e.g. this works:

            <xamanimation:StoryBoard x:Key="LogoAnimation" Target="{x:Reference Logo}">
                <xamanimation:TranslateToAnimation TranslateY="500" Duration="0" />
                <xamanimation:TranslateToAnimation
                    Easing="SpringOut"
                    TranslateY="0"
                    Duration="750" />
            </xamanimation:StoryBoard>

The fix for me was to instead just do only <xamanimation:FadeToAnimation Opacity="1" Duration="500" /> and set the Opacity="0" explicitly on the Target Grid.

Here was the error in the former case:

System.Private.Interop.dll!System.Runtime.InteropServices.McgMarshal.ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd) Line 1189 at f:\dd\ndp\fxcore\CoreRT\src\System.Private.Interop\src\Shared\McgMarshal.cs(1189)

System.ArgumentException HResult=0x80070057 Message=Value does not fall within the expected range. Source= StackTrace: StackTrace " at System.Runtime.InteropServices.McgMarshal.ThrowOnExternalCallFailed(Int32 hr, RuntimeTypeHandle typeHnd) in f:\dd\ndp\fxcore\CoreRT\src\System.Private.Interop\src\Shared\McgMarshal.cs:line 1189\r\n at __Interop.ComCallHelpers.Call(__ComObject __this, RuntimeTypeHandle __typeHnd, Int32 __targetIndex, Double arg0)\r\n
at __Interop.ForwardComStubs.Stub_22[TThis](__ComObject __this, Double value, Int32 __targetIndex)\r\n at Windows.UI.Xaml.IUIElement__Impl.Stubs.put_Opacity(__ComObject __this, Double value)\r\n at Windows.UI.Xaml.UIElement.put_Opacity(Double value)\r\n at Xamarin.Forms.Platform.UWP.VisualElementTracker2.UpdateOpacity(VisualElement
view, FrameworkElement frameworkElement) in
D:\a\1\s\Xamarin.Forms.Platform.UAP\VisualElementTracker.cs:line
518\r\n at
Xamarin.Forms.Platform.UWP.VisualElementTracker2.UpdateNativeControl() in D:\a\1\s\Xamarin.Forms.Platform.UAP\VisualElementTracker.cs:line 236\r\n at Xamarin.Forms.Platform.UWP.VisualElementTracker2.OnRedrawNeeded(Object
sender, EventArgs e) in
D:\a\1\s\Xamarin.Forms.Platform.UAP\VisualElementTracker.cs:line
409\r\n at System.EventHandler1.Invoke(Object sender, TEventArgs e)\r\n at Xamarin.Forms.VisualElement.BatchCommit() in D:\a\1\s\Xamarin.Forms.Core\VisualElement.cs:line 572\r\n at Xamarin.Forms.AnimationExtensions.HandleTweenerUpdated(Object o, EventArgs args) in D:\a\1\s\Xamarin.Forms.Core\AnimationExtensions.cs:line 274\r\n
at System.EventHandler.InvokeOpenStaticThunk(Object sender, EventArgs e)\r\n at System.EventHandler.Invoke(Object sender, EventArgs e)\r\n at Xamarin.Forms.Tweener.b__22_0(Int64 step) in D:\a\1\s\Xamarin.Forms.Core\Tweener.cs:line 92\r\n at System.Func2.Invoke(T arg)\r\n at
Xamarin.Forms.Internals.Ticker.SendSignals(Int64 step) in
D:\a\1\s\Xamarin.Forms.Core\Internals\Ticker.cs:line 136\r\n

at Xamarin.Forms.Internals.Ticker.SendSignals(Int32 timestep) in
D:\a\1\s\Xamarin.Forms.Core\Internals\Ticker.cs:line 125\r\n

at
Xamarin.Forms.Platform.UWP.WindowsTicker.RenderingFrameEventHandler(Object
sender, Object args) in
D:\a\1\s\Xamarin.Forms.Platform.UAP\WindowsTicker.cs:line 25\r\n
at System.EventHandler1.Invoke(Object sender, TEventArgs e)\r\n at __Interop.Intrinsics.HasThisCall__51(Object __this, IntPtr pfn, Object arg0, Object arg1)\r\n at __Interop.ReverseComStubs.Stub_41(Object __this, Void* unsafe_sender, Void* unsafe_args, IntPtr __methodPtr)" string

Number of movements in ShakeAnimation

Hello Javier!

Before everything, I want to thank you for this amazing lib!

I'm using the lib in my project to animate some entries with Shake Animation when user inserts invalid values.
Talking with the UX professional in my team, she asked me if it is possible to control the number of movements in the shake animation.

Looking at the code, I saw that the class ShakeAnimation have the property Movement but it is private and I can't change it.

What do you think about creating a bindable property for this? With this, the user will be able to control the number of movements in the animation

Thank you!

how to prevent heartanimation to increase size of the tool?

Using heart animation on a label with a button click, if user taps the button sequentially so fast ,it increases the size of the label. how can we prevent it?

I tried below but it doesnt help.


 private void btnAddItemTapped(object sender, EventArgs e)
        {
            if (IsAnimating)
                return;

            IsAnimating = true;
            lblTest.Animate(new HeartAnimation());
            IsAnimating = false;
          
        }
        bool IsAnimating = false;

EntranceTransition and Prism

Using EntranceTransition, when I call a Dialog with Prism, the animation starts again on the background page. When I close the Dialog, the animation runs again on the page.

`var b = new EntranceTransition
{
Duration = "300"
};

        mainGrid.Behaviors.Add(b);`

dialogService.ShowDialog("NovidadesView", CloseDialogCallback);

How can I stop this from happening? I tried to track down the "Renderer" property changed on my page, removing the Behavior, but it seems to be spread to all components inside the mainGrid.

Flip doesnt work on UWP

using XF 3.0 and latest UWP update as below, flip doesnt do anything on UWP local desktop

image

Binding is null

this example:
<controls:ExtenderSwitch Grid.Row="8"
Grid.Column="1"
IsEnabled="{Binding IsEditing}"
IsToggled="{Binding Customizing.IsShoppingOnline, Mode=TwoWay}"
Style="{StaticResource CustomizingCard.CardSwitch}">
controls:ExtenderSwitch.Triggers

xamanimation:BeginAnimation
xamanimation:BeginAnimation.Animation
<xamanimation:FadeToAnimation Target="{x:Reference FadeBox}"
Duration="2000"
Opacity="{Binding Customizing.IsShoppingOnline, Converter={StaticResource BoolToHeightConverter}, ConverterParameter=1}" />
</xamanimation:BeginAnimation.Animation>
</xamanimation:BeginAnimation>

</controls:ExtenderSwitch.Triggers>
</controls:ExtenderSwitch>

The FadeToAnimation.BindingContext is null, since, BeginAnimation not bindingContext to BaseAnimation.

Help: What is the best approach for animating a object in View when using MVVM?

Hello,

I have a simple Xamarin Forms app. I am using Prism Forms. I would like to animate Label with basic fade animation in View, when its old value and new value is not equal. What is the best approach for animating a object in View? Thank you in advance.

MainPageViewModel.cs


public class MainPageViewModel : BindableBase
{
    public HomePageViewModel()
    {       
            Title = "First";
            ChangeTitle();
    }

    private async void ChangeTitle()
    {

        await Task.Delay(5000);

        if(Title == "First")
        {
            Title = "Second";
        }
        else
        {
            Title = "First";
        }

        ChangeTitle();
    }



    private string title;
    public string Title
    {
        get { return title; }
        set { SetProperty(ref title, value); }
    }

}

MainPage.xml

<ContentPage
    x:Class="SmapleApp.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:prism="http://prismlibrary.com"
    prism:ViewModelLocator.AutowireViewModel="True"
    Title="Main Page">

    <Label Text="{Binding Title}" />

</ContentPage>

[Feature Request] Reposition Transition

Summary

Reposition Transition is an animation that reacts to layout moves.
Personally i trigger this Reposition transition with Visual states manager's Adaptive trigers in UWP when size of the window changes and want an item get bigger or move somewhere .

WHY?

Xamarin.Forms is not only UWP (or every desktop platforms or even WASM) ? sure but there's iPads and android tablets with split windows now or even surface duo (which is kinda a phone) when you expand the app in two screens or collapse to one.
not a big deal for regular phones but it can even have a little animations for them! when you rotate your phone items move with animation (Example : collectionview span changes from 1 to 2 when you rotate )

APIs

i donno this link is useful for you or not :( but here is the WinUI one
https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.animation.repositionthemetransition?view=winrt-18362

Platforms

Core/Xaml (All Platforms)
UWP
Android
iOS

c# documentation request for simple things

Hi, this plugin looks great but I have no idea how am I supposed to use your API to call an animation in C#. Please provide examples.

On this page all you say is we can do myElement.Animate(new FadeOutAnimation());
How do I define how long it lasts?
How do I pass in a callback Action for when it is done animating so I can disable myElement?

Your other AnimationExtensions overloads are super confusing as well:

  • string name? what's the name? why do I need to come up with one by default?
  • second param takes Animation but not Xamanimation.Animation??? How do I say start a xamanimation FadeOutAnimation then??
  • finished callback is an Action<double,bool>?? What does it need a double and a bool? What are those parameters for? I just want to run an arbitrary action when the animation is done.
  • repeat is a Func?? Bool? What does that mean? Shouldn't it be an int howManyTimes with 0 being infinite and -1 false?

So okay back to trying FadeOutAnimation(), let's try to give it a length and find if it has an OnFinished callback or make my own..:

  • Xamanimation.AnimationBase anim = new FadeOutAnimation(); Then I try to do anim.Duration = 1; What? It's a string? Why??? What do I write there? Milliseconds? Format? Am I even supposed to use this or is it for something else?
  • Callbacks? No callbacks.

I've never been more confused. Please provide some kind of explanation for what you're providing here.

ibtool exit code 1

when i compile on vs4mac i get error ibltool exit code 1.
It does not run

:(

Feature request: Looping animations

First of all thanks for that nice little library! I'm using this to get some simple animations done, but it would be awesome to also get the opportunity to loop animations (e.g. pulsating animations to draw the users attention).

Xaml only animations fail to load Xamanimation.dll

After creating a new cross-platform project/solution and adding the Xamanimation reference (nuget) to the PCL, when deploying to iOS the application crashes with the following exception:

Xamarin.Forms.Xaml.XamlParseException: Position 8:14. Type xamanimation:FadeToAnimation not found in xmlns clr-namespace:Xamanimation;assembly=Xamanimation

If I add the following to the xaml code behind the application will load on iOS:

FadeBox.Animate(new FadeToAnimation());'

Using the Xamanimation Sample project you can test this same behavior by commenting out the code below IntializeComponent() in the AnimationsView.xaml.cs file. That is, comment out the AnimationExtensionButton click event handler code. By commenting out the code, the Xamanimation.dll will no longer load and the sample app will crash at startup.

Easing Functions

Does this library provide easing functions or at least for a way to add them?

Listview item

Is it possible to animate a cell of a listview? Can you provide a sample of code?

AnimateProgressColor seems always black

Hello firstly thank you for your great plugin. The following codes are not working properly. xHeader's backgroud always seems black.

 <ContentView
            x:Name="xHeader"
            Grid.Row="0"
            BackgroundColor="Green"
            HeightRequest="90"
            IsClippedToBounds="True"
            VerticalOptions="StartAndExpand">

<xamanimation:AnimateProgressColor
                    Maximum="200"
                    Minimum="0"
                    Progress="{Binding ScrollY, Source={x:Reference ScrollBehavior}}"
                    TargetProperty="VisualElement.BackgroundColor"
                    From="Yellow"
                    To="Green" />

</ContentView>
 <ScrollView
            Margin="0"
            CascadeInputTransparent="False"
            HorizontalOptions="Fill"
            HorizontalScrollBarVisibility="Never"
            InputTransparent="False"
            IsEnabled="True"
            VerticalOptions="FillAndExpand"
            VerticalScrollBarVisibility="Never">

            <VisualElement.Behaviors>
                <xamanimation:ScrollViewScrollBehavior x:Name="ScrollBehavior" />
            </VisualElement.Behaviors>
</ScrollView>

Thank you in advance

Please support .net standard

Maybe this project is not support standard yet
Please support...
I'm using this very well beacause of you. Thanks

EntranceTransition adds vertical offset to animated elements

I'm using EntranceTransition on each item in a FlexLayout.
The animation itself works fine but the animated elements layout gets messed up. Seems like descendant elements are added with some padding.
I compiled the library locally and noticed this line: const int TranslateFrom = 6;
So I changed to 0 and voila - the layout is now fine.

ShakeAnimation with RepeatForever and Triggers

Hello,
I try to use ShakeAnimation with repeatForever and Trigger in this way

<Label x:Name="AllarmeBox" Text="text to show" FontSize="Large" IsVisible="{Binding IsLabelVisible}"
                   HorizontalTextAlignment="Center" VerticalTextAlignment="Center">

                <Label.Triggers>

                        <Trigger TargetType="Label" Property="IsVisible" Value="True">
                            <Trigger.EnterActions>
                                <xamanimation:BeginAnimation Animation="{StaticResource ShakeAnimationIn}" />
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <xamanimation:BeginAnimation Animation="{StaticResource ShakeAnimationOut}" />
                            </Trigger.ExitActions>
                        </Trigger>

                </Label.Triggers>
            </Label>

having in the resources:

            <xamanimation:ShakeAnimation
                x:Key="ShakeAnimationIn"
                RepeatForever="True"
                Target="{x:Reference AllarmeBox}"/>

            <xamanimation:ShakeAnimation
                x:Key="ShakeAnimationOut"
                Target="{x:Reference AllarmeBox}"/>

The problem is that using RepeatForever="True" the label is not shown...
maybe multiple shake animation starts on the same label, without waiting the previous animation ends?

ps
Using only ShakeAnimationOut (without RepeatForever) the single animation is shown

Update:
In your sample, if you add RepeatForever="True" on ShakeAnimation, you can see the box moving out of screen
Maybe the 'next animation' should starts after the animation previous animation ends ('Duration' parameter)

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.