AndroidSurfaceRenderer.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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(Urho.Forms.UrhoSurface), typeof(AndroidSurfaceRenderer))]
  12. namespace Urho.Forms
  13. {
  14. public class AndroidSurfaceRenderer : ViewRenderer<Urho.Forms.UrhoSurface, AndroidUrhoSurface>
  15. {
  16. protected override void OnElementChanged(ElementChangedEventArgs<Urho.Forms.UrhoSurface> e)
  17. {
  18. SDLActivity.OnResume();
  19. var surface = new AndroidUrhoSurface(Context);
  20. if (e.NewElement == null)
  21. return;
  22. e.NewElement.RegisterRunner(surface.Launcher);
  23. SetNativeControl(surface);
  24. base.OnElementChanged(e);
  25. }
  26. }
  27. public class AndroidUrhoSurface : FrameLayout
  28. {
  29. static readonly SemaphoreSlim launcherSemaphore = new SemaphoreSlim(1);
  30. FrameLayout surfaceViewPlaceholder;
  31. Urho.Droid.UrhoSurfacePlaceholder surfaceView;
  32. public AndroidUrhoSurface(Android.Content.Context context) : base(context)
  33. {
  34. AddView(surfaceViewPlaceholder = new FrameLayout(Context));
  35. }
  36. protected override void OnLayout(bool changed, int l, int t, int r, int b)
  37. {
  38. surfaceViewPlaceholder.Measure(
  39. MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly),
  40. MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly));
  41. surfaceViewPlaceholder.Layout(0, 0, r - l, b - t);
  42. }
  43. internal async Task<Urho.Application> Launcher(Type type, ApplicationOptions options)
  44. {
  45. await launcherSemaphore.WaitAsync();
  46. Urho.Application.StopCurrent();
  47. surfaceViewPlaceholder.RemoveAllViews();
  48. surfaceView = Urho.Droid.UrhoSurface.CreateSurface((Activity)Context);
  49. surfaceViewPlaceholder.AddView(surfaceView);
  50. var app = await surfaceView.Show(type, options);
  51. launcherSemaphore.Release();
  52. return app;
  53. }
  54. }
  55. }