PlatformRenderInterface.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Avalonia.Controls.Platform.Surfaces;
  6. using Avalonia.Media;
  7. using Avalonia.Platform;
  8. using SkiaSharp;
  9. namespace Avalonia.Skia
  10. {
  11. public partial class PlatformRenderInterface : IPlatformRenderInterface
  12. {
  13. public IBitmapImpl CreateBitmap(int width, int height)
  14. {
  15. return CreateRenderTargetBitmap(width, height, 96, 96);
  16. }
  17. public IFormattedTextImpl CreateFormattedText(
  18. string text,
  19. Typeface typeface,
  20. TextAlignment textAlignment,
  21. TextWrapping wrapping,
  22. Size constraint,
  23. IReadOnlyList<FormattedTextStyleSpan> spans)
  24. {
  25. return new FormattedTextImpl(text, typeface, textAlignment, wrapping, constraint, spans);
  26. }
  27. public IStreamGeometryImpl CreateStreamGeometry()
  28. {
  29. return new StreamGeometryImpl();
  30. }
  31. public IBitmapImpl LoadBitmap(System.IO.Stream stream)
  32. {
  33. using (var s = new SKManagedStream(stream))
  34. {
  35. var bitmap = SKBitmap.Decode(s);
  36. if (bitmap != null)
  37. {
  38. return new BitmapImpl(bitmap);
  39. }
  40. else
  41. {
  42. throw new ArgumentException("Unable to load bitmap from provided data");
  43. }
  44. }
  45. }
  46. public IBitmapImpl LoadBitmap(string fileName)
  47. {
  48. using (var stream = File.OpenRead(fileName))
  49. {
  50. return LoadBitmap(stream);
  51. }
  52. }
  53. public IBitmapImpl LoadBitmap(PixelFormat format, IntPtr data, int width, int height, int stride)
  54. {
  55. using (var tmp = new SKBitmap())
  56. {
  57. tmp.InstallPixels(new SKImageInfo(width, height, format.ToSkColorType(), SKAlphaType.Premul)
  58. , data, stride);
  59. return new BitmapImpl(tmp.Copy());
  60. }
  61. }
  62. public IRenderTargetBitmapImpl CreateRenderTargetBitmap(
  63. int width,
  64. int height,
  65. double dpiX,
  66. double dpiY)
  67. {
  68. if (width < 1)
  69. throw new ArgumentException("Width can't be less than 1", nameof(width));
  70. if (height < 1)
  71. throw new ArgumentException("Height can't be less than 1", nameof(height));
  72. return new BitmapImpl(width, height);
  73. }
  74. public virtual IRenderTarget CreateRenderTarget(IEnumerable<object> surfaces)
  75. {
  76. var fb = surfaces?.OfType<IFramebufferPlatformSurface>().FirstOrDefault();
  77. if (fb == null)
  78. throw new Exception("Skia backend currently only supports framebuffer render target");
  79. return new FramebufferRenderTarget(fb);
  80. }
  81. public IWritableBitmapImpl CreateWritableBitmap(int width, int height, PixelFormat? format = null)
  82. {
  83. return new BitmapImpl(width, height, format);
  84. }
  85. }
  86. }