AndroidSurfaceRenderer.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Android.App;
  5. using Android.Views;
  6. using Android.Widget;
  7. using Org.Libsdl.App;
  8. using Urho.Forms;
  9. using Xamarin.Forms;
  10. using Xamarin.Forms.Platform.Android;
  11. [assembly: ExportRendererAttribute(typeof(UrhoSurface), typeof(AndroidSurfaceRenderer))]
  12. namespace Urho.Forms
  13. {
  14. public class AndroidSurfaceRenderer : ViewRenderer<UrhoSurface, AndroidUrhoSurface>
  15. {
  16. protected override void OnElementChanged(ElementChangedEventArgs<UrhoSurface> e)
  17. {
  18. SDLActivity.OnResume();
  19. var surface = new AndroidUrhoSurface(Context);
  20. e.NewElement.UrhoApplicationLauncher = surface.Launcher;
  21. SetNativeControl(surface);
  22. base.OnElementChanged(e);
  23. }
  24. }
  25. public class AndroidUrhoSurface : FrameLayout
  26. {
  27. static TaskCompletionSource<Application> applicationTaskSource;
  28. static readonly SemaphoreSlim launcherSemaphore = new SemaphoreSlim(1);
  29. readonly FrameLayout surfaceViewPlaceholder;
  30. public AndroidUrhoSurface(Android.Content.Context context) : base(context)
  31. {
  32. AddView(surfaceViewPlaceholder = new FrameLayout(Context));
  33. }
  34. protected override void OnLayout(bool changed, int l, int t, int r, int b)
  35. {
  36. surfaceViewPlaceholder.Measure(
  37. MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly),
  38. MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly));
  39. surfaceViewPlaceholder.Layout(0, 0, r - l, b - t);
  40. }
  41. internal async Task<Urho.Application> Launcher(Type type, ApplicationOptions options)
  42. {
  43. await launcherSemaphore.WaitAsync();
  44. SDLActivity.OnDestroy();
  45. surfaceViewPlaceholder.RemoveAllViews();
  46. applicationTaskSource = new TaskCompletionSource<Application>();
  47. Urho.Application.Started += UrhoApplicationStarted;
  48. var surfaceView = Urho.Droid.UrhoSurface.CreateSurface((Activity)Context, type, options);
  49. SDLActivity.OnResume();
  50. surfaceViewPlaceholder.AddView(surfaceView);
  51. return await applicationTaskSource.Task;
  52. }
  53. void UrhoApplicationStarted()
  54. {
  55. Urho.Application.Started -= UrhoApplicationStarted;
  56. applicationTaskSource?.TrySetResult(Application.Current);
  57. launcherSemaphore.Release();
  58. }
  59. }
  60. }