RenderTarget.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Runtime.InteropServices;
  5. using Avalonia.Cairo.Media;
  6. using Avalonia.Media;
  7. using Avalonia.Platform;
  8. using Avalonia.Rendering;
  9. using Gtk;
  10. using DrawingContext = Avalonia.Media.DrawingContext;
  11. namespace Avalonia.Cairo
  12. {
  13. using global::Cairo;
  14. /// <summary>
  15. /// A cairo render target.
  16. /// </summary>
  17. public class RenderTarget : IRenderTarget
  18. {
  19. private readonly Surface _surface;
  20. private readonly Gtk.Window _window;
  21. private readonly Gtk.DrawingArea _area;
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="RenderTarget"/> class.
  24. /// </summary>
  25. /// <param name="window">The window.</param>
  26. /// <param name="width">The width of the window.</param>
  27. /// <param name="height">The height of the window.</param>
  28. public RenderTarget(Gtk.Window window)
  29. {
  30. _window = window;
  31. }
  32. public RenderTarget(ImageSurface surface)
  33. {
  34. _surface = surface;
  35. }
  36. public RenderTarget(DrawingArea area)
  37. {
  38. _area = area;
  39. }
  40. /// <summary>
  41. /// Creates a cairo surface that targets a platform-specific resource.
  42. /// </summary>
  43. /// <returns>A surface wrapped in an <see cref="Avalonia.Media.DrawingContext"/>.</returns>
  44. public DrawingContext CreateDrawingContext() => new DrawingContext(CreateMediaDrawingContext());
  45. public IDrawingContextImpl CreateMediaDrawingContext()
  46. {
  47. if(_window!=null)
  48. return new Media.DrawingContext(_window.GdkWindow);
  49. if (_surface != null)
  50. return new Media.DrawingContext(_surface);
  51. if(_area!=null)
  52. return new Media.DrawingContext(_area.GdkWindow);
  53. throw new InvalidOperationException();
  54. }
  55. public void Dispose() => _surface?.Dispose();
  56. }
  57. }