InvalidationAwareSurfaceView.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using Android.Content;
  3. using Android.Graphics;
  4. using Android.OS;
  5. using Android.Util;
  6. using Android.Views;
  7. using Avalonia.Platform;
  8. namespace Avalonia.Android
  9. {
  10. public abstract class InvalidationAwareSurfaceView : SurfaceView, ISurfaceHolderCallback, IPlatformHandle
  11. {
  12. bool _invalidateQueued;
  13. readonly object _lock = new object();
  14. private readonly Handler _handler;
  15. public InvalidationAwareSurfaceView(Context context) : base(context)
  16. {
  17. Holder.AddCallback(this);
  18. _handler = new Handler(context.MainLooper);
  19. }
  20. public override void Invalidate()
  21. {
  22. lock (_lock)
  23. {
  24. if(_invalidateQueued)
  25. return;
  26. _handler.Post(() =>
  27. {
  28. if (Holder.Surface?.IsValid != true)
  29. return;
  30. try
  31. {
  32. DoDraw();
  33. }
  34. catch (Exception e)
  35. {
  36. Log.WriteLine(LogPriority.Error, "Avalonia", e.ToString());
  37. }
  38. });
  39. }
  40. }
  41. public override void Invalidate(global::Android.Graphics.Rect dirty)
  42. {
  43. Invalidate();
  44. }
  45. public override void Invalidate(int l, int t, int r, int b)
  46. {
  47. Invalidate();
  48. }
  49. public void SurfaceChanged(ISurfaceHolder holder, Format format, int width, int height)
  50. {
  51. Log.Info("AVALONIA", "Surface Changed");
  52. DoDraw();
  53. }
  54. public void SurfaceCreated(ISurfaceHolder holder)
  55. {
  56. Log.Info("AVALONIA", "Surface Created");
  57. DoDraw();
  58. }
  59. public void SurfaceDestroyed(ISurfaceHolder holder)
  60. {
  61. Log.Info("AVALONIA", "Surface Destroyed");
  62. }
  63. protected void DoDraw()
  64. {
  65. lock (_lock)
  66. {
  67. _invalidateQueued = false;
  68. }
  69. Draw();
  70. }
  71. protected abstract void Draw();
  72. public string HandleDescriptor => "SurfaceView";
  73. }
  74. }