Code Monkey home page Code Monkey logo

Comments (4)

neech avatar neech commented on September 22, 2024

Code proposal
I add " canvas.Scale(AnimationScaleX, AnimationScaleY, info.Width/2, info. Height/2);" in OnPaintSurface, this will allow the user to scale in the center.

`using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using SkiaSharp;
using SkiaSharp.Skottie;
using SkiaSharp.Views.Desktop;
using SkiaSharp.Views.WPF;

namespace LottieSharp.WPF
{
public class LottieAnimationView : SKElement
{
private readonly Stopwatch watch = new();
private Animation animation;
private DispatcherTimer timer;
private int loopCount;

    public AnimationInfo Info
    {
        get { return (AnimationInfo)GetValue(InfoProperty); }
        set { SetValue(InfoProperty, value); }
    }

    public event EventHandler OnStop;

    public string FileName
    {
        get => (string)GetValue(FileNameProperty);
        set => SetValue(FileNameProperty, value);
    }

    public string ResourcePath
    {
        get => (string)GetValue(ResourcePathProperty);
        set => SetValue(ResourcePathProperty, value);
    }

    public float AnimationScaleX
    {
        get => (float)GetValue(AnimationScaleXProperty);
        set => SetValue(AnimationScaleXProperty, value);
    }
    public float AnimationScaleY
    {
        get => (float)GetValue(AnimationScaleYProperty);
        set => SetValue(AnimationScaleYProperty, value);
    }
    public virtual void PlayAnimation()
    {
        timer.Start();
        watch.Start();
        IsPlaying = true;
    }

    public virtual void StopAnimation()
    {
        loopCount = RepeatCount;
        timer.Stop();
        watch.Reset();
        IsPlaying = false;

        OnStop?.Invoke(this, null);
    }

    public int RepeatCount
    {
        get { return (int)GetValue(RepeatCountProperty); }
        set { SetValue(RepeatCountProperty, value); }
    }

    public static readonly DependencyProperty RepeatCountProperty =
        DependencyProperty.Register("RepeatCount", typeof(int), typeof(LottieAnimationView), new PropertyMetadata(0, RepeatCountChangedCallback));

    private static void RepeatCountChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is LottieAnimationView lottieAnimationView)
        {
            lottieAnimationView.loopCount = (int)e.NewValue;
        }
    }

    public bool AutoPlay
    {
        get { return (bool)GetValue(AutoStartProperty); }
        set { SetValue(AutoStartProperty, value); }
    }

    public static readonly DependencyProperty AutoStartProperty =
        DependencyProperty.Register("AutoPlay", typeof(bool), typeof(LottieAnimationView), new PropertyMetadata(false, AutoPlayPropertyChangedCallback));

    public static readonly DependencyProperty InfoProperty =
        DependencyProperty.Register("Info", typeof(AnimationInfo), typeof(LottieAnimationView));

    private static void AutoPlayPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        // Not in use at the moment
    }

    public bool IsPlaying
    {
        get { return (bool)GetValue(IsPlayingProperty); }
        set { SetValue(IsPlayingProperty, value); }
    }

    public static readonly DependencyProperty IsPlayingProperty =
        DependencyProperty.Register("IsPlaying", typeof(bool), typeof(LottieAnimationView), new PropertyMetadata(false));

    public RepeatMode Repeat
    {
        get { return (RepeatMode)GetValue(RepeatProperty); }
        set { SetValue(RepeatProperty, value); }
    }

    public static readonly DependencyProperty RepeatProperty =
        DependencyProperty.Register("Repeat", typeof(RepeatMode), typeof(LottieAnimationView), new PropertyMetadata(RepeatMode.Restart));

    public static readonly DependencyProperty FileNameProperty =
        DependencyProperty.Register("FileName", typeof(string), typeof(LottieAnimationView), new PropertyMetadata(null, FileNamePropertyChangedCallback));

    public static readonly DependencyProperty ResourcePathProperty =
        DependencyProperty.Register("ResourcePath", typeof(string), typeof(LottieAnimationView), new PropertyMetadata(null, ResourcePathPropertyChangedCallback));

    public static readonly DependencyProperty AnimationScaleXProperty =
      DependencyProperty.Register("AnimationScaleX", typeof(float), typeof(LottieAnimationView), new PropertyMetadata((float)1.0));

    public static readonly DependencyProperty AnimationScaleYProperty =
      DependencyProperty.Register("AnimationScaleY", typeof(float), typeof(LottieAnimationView), new PropertyMetadata((float)1.0));

    private static void FileNamePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        if (dependencyObject is LottieAnimationView lottieAnimationView && e.NewValue is string assetName)
        {
            lottieAnimationView.SetAnimationFromFile(assetName);
        }
    }

    private static void ResourcePathPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        if (dependencyObject is LottieAnimationView lottieAnimationView && e.NewValue is string assetName)
        {
            lottieAnimationView.SetAnimationFromResource(assetName);
        }
    }

    private void SetAnimationFromFile(string assetName)
    {
        try
        {
            using FileStream stream = File.OpenRead(assetName);
            SetAnimation(stream);
        }
        catch (IOException)
        {
            Debug.WriteLine($"Failed to load {assetName}");
            throw;
        }
        catch (Exception)
        {
            Debug.WriteLine($"Unexpected error when loading {assetName}");
            throw;
        }
    }

    private void SetAnimationFromResource(string assetUri)
    {
        if (DesignerProperties.GetIsInDesignMode(this))
        {
            return;
        }

        try
        {
            var resourceUri = new Uri(assetUri);
            var resourceInfo = Application.GetResourceStream(resourceUri);

            SetAnimation(resourceInfo?.Stream);
        }
        catch (IOException)
        {
            Debug.WriteLine($"Failed to load resource {assetUri}");
            throw;
        }
        catch (UriFormatException)
        {
            Debug.WriteLine($"Resource URI failure for resource {assetUri}");
            throw;
        }
        catch (Exception)
        {
            Debug.WriteLine($"Unexpected error when loading resource {assetUri}");
            throw;
        }

    }

    private void SetAnimation(Stream stream)
    {


        using SKManagedStream fileStream = new(stream);

        if (Animation.TryCreate(fileStream, out animation))
        {
            animation.Seek(0);
            Info = new AnimationInfo(animation.Version, animation.Duration, animation.Fps, animation.InPoint,
                animation.OutPoint);
        }
        else
        {
            Info = new AnimationInfo(string.Empty, TimeSpan.Zero, 0, 0, 0);
            throw new InvalidOperationException("Failed to load animation");
        }

        watch.Reset();
        if (timer == null)
        {
            timer = new DispatcherTimer(DispatcherPriority.Render);
            timer.Interval = TimeSpan.FromSeconds(Math.Max(1 / 60.0, 1 / animation.Fps));
            timer.Tick += (s, e) => { InvalidateVisual(); };
        }
        else
        {
            timer.Stop();
            timer.Interval = TimeSpan.FromSeconds(Math.Max(1 / 60.0, 1 / animation.Fps));
        }

        if (AutoPlay || IsPlaying)
        {
            PlayAnimation();
        }
    }

    protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
    {
        base.OnPaintSurface(e);

        SKCanvas canvas = e.Surface.Canvas;
        canvas.Clear(SKColor.Empty);
        SKImageInfo info = e.Info;

        if (animation != null)
        {
            animation.SeekFrameTime((float)watch.Elapsed.TotalSeconds);

            if (watch.Elapsed.TotalSeconds > animation.Duration.TotalSeconds)
            {
                if (Repeat == RepeatMode.Restart)
                {
                    if (RepeatCount == Defaults.RepeatCountInfinite)
                    {
                        watch.Restart();
                    }
                    else if (RepeatCount > 0 && loopCount > 0)
                    {
                        loopCount--;
                        watch.Restart();
                    }
                    else
                    {
                        StopAnimation();
                    }
                }
            }


   
           canvas.Scale(AnimationScaleX, AnimationScaleY, info.Width/2, info.Height/2);
            animation.Render(canvas, new SKRect(0, 0, info.Width, info.Height));
        }
    }
}

}
`

from lottiesharp.

quicoli avatar quicoli commented on September 22, 2024

Hi @neech,

This is interesting. Thank you for your suggestion, it's important that users give some insights of their real use so we can implement things that are important.
I'll include this in the next release, the implementation might be a bit different... having something like:

<CenterAnimationScale>
      <ScaleTransform ScaleX = "1.5" ScaleY="1.5"/>
</CenterAnimationScale>

from lottiesharp.

neech avatar neech commented on September 22, 2024

@quicoli thank you very much.
It may be also useful to be able to use the x and y coordinate offset

from lottiesharp.

quicoli avatar quicoli commented on September 22, 2024

In release 2.2.0

from lottiesharp.

Related Issues (20)

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.