1

I'm trying to make a very basic animation with SkiaSharp in Xamarin. Basically a small point spinning in a circle. A basic Timer does the job, however i can't keep a consistent speed for the animation across different devices. The speed of the animation changes drastically based on the screen size (for example if i switch to Landscape the animation is about half as slow).

This is my code:

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

    SKSurface surface = e.Surface;
    SKCanvas canvas = surface.Canvas;

    canvas.Clear();

    int width = e.Info.Width;
    int height = e.Info.Height;

    canvas.Translate(width / 2, height / 2);
    canvas.Scale(0.2f, 0.2f);
    canvas.Save();
    float radiusDot = radius * 8;
    canvas.DrawCircle((float)(radiusDot * Math.Sin(degree * (Math.PI / 180))), (float)(radiusDot * Math.Cos(degree * (Math.PI / 180))), 100, blueFillPoint);
    canvas.Restore();
    canvas.Save();
}

and the timers:

Device.StartTimer(TimeSpan.FromMilliseconds(5), () =>
{
    if (degree == 0) degree = 360;
    else degree -= 2;
    if (degreeTail == 360) degreeTail = 0;
    else degreeTail += 2;
    return true;
});

Device.StartTimer(TimeSpan.FromSeconds(1f / 120), () =>
{
    this.InvalidateSurface();
    return true;
});
Elias Johannes
  • 694
  • 2
  • 7
  • 26
  • first, try using System.Timers.Timer instead – Jason Nov 02 '19 at 21:45
  • I usually always prefere `System.Timers.Timer` over the Device Timer but in this case for some reason i don't understand, with the System Timer the SkiaSharp canvas doesn't refresh automatically (only when i change orientation) – Elias Johannes Nov 02 '19 at 22:55
  • Device.StartTimer is probably running on the UI thread – Jason Nov 02 '19 at 22:58
  • You are right Jason. Inside the function that i'm calling with my `System.Timers.Timer` i invoked the code in the MainThread and now i got a synchronous animation on every screen resolution. Feel free to post an answer so i can mark it as accepted. – Elias Johannes Nov 02 '19 at 23:02
  • 5ms is a little bit too low - will teoretically yield in 200 fps. – Michal Dobrodenka Nov 09 '19 at 05:58

0 Answers0