D2DBitmapImpl.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.IO;
  3. using SharpDX.Direct2D1;
  4. using ImagingFactory2 = SharpDX.WIC.ImagingFactory2;
  5. using ImageParameters = SharpDX.WIC.ImageParameters;
  6. using PngBitmapEncoder = SharpDX.WIC.PngBitmapEncoder;
  7. namespace Avalonia.Direct2D1.Media
  8. {
  9. /// <summary>
  10. /// A Direct2D Bitmap implementation that uses a GPU memory bitmap as its image.
  11. /// </summary>
  12. public class D2DBitmapImpl : BitmapImpl
  13. {
  14. private Bitmap _direct2DBitmap;
  15. /// <summary>
  16. /// Initialize a new instance of the <see cref="BitmapImpl"/> class
  17. /// with a bitmap backed by GPU memory.
  18. /// </summary>
  19. /// <param name="d2DBitmap">The GPU bitmap.</param>
  20. /// <remarks>
  21. /// This bitmap must be either from the same render target,
  22. /// or if the render target is a <see cref="SharpDX.Direct2D1.DeviceContext"/>,
  23. /// the device associated with this context, to be renderable.
  24. /// </remarks>
  25. public D2DBitmapImpl(Bitmap d2DBitmap)
  26. {
  27. _direct2DBitmap = d2DBitmap ?? throw new ArgumentNullException(nameof(d2DBitmap));
  28. }
  29. public override int PixelWidth => _direct2DBitmap.PixelSize.Width;
  30. public override int PixelHeight => _direct2DBitmap.PixelSize.Height;
  31. public override void Dispose()
  32. {
  33. base.Dispose();
  34. _direct2DBitmap.Dispose();
  35. }
  36. public override OptionalDispose<Bitmap> GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget target)
  37. {
  38. return new OptionalDispose<Bitmap>(_direct2DBitmap, false);
  39. }
  40. public override void Save(Stream stream)
  41. {
  42. using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream))
  43. using (var frameEncode = new SharpDX.WIC.BitmapFrameEncode(encoder))
  44. //ToDo: Not supported under Windows 7!
  45. using (var imageEncoder = new SharpDX.WIC.ImageEncoder((ImagingFactory2)Direct2D1Platform.ImagingFactory, null))
  46. {
  47. var parameters = new ImageParameters(
  48. new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
  49. _direct2DBitmap.DotsPerInch.Width,
  50. _direct2DBitmap.DotsPerInch.Height,
  51. 0, 0, PixelWidth, PixelHeight);
  52. imageEncoder.WriteFrame(_direct2DBitmap, frameEncode, parameters);
  53. frameEncode.Commit();
  54. encoder.Commit();
  55. }
  56. }
  57. }
  58. }