SurfaceRenderer.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using PixiEditor.Models.DataHolders;
  2. using SkiaSharp;
  3. using System;
  4. using System.Windows;
  5. using System.Windows.Media;
  6. using System.Windows.Media.Imaging;
  7. namespace PixiEditor.Models.Controllers
  8. {
  9. class SurfaceRenderer : IDisposable
  10. {
  11. public SKSurface BackingSurface { get; private set; }
  12. public WriteableBitmap FinalBitmap { get; private set; }
  13. private SKPaint BlendingPaint { get; } = new SKPaint() { BlendMode = SKBlendMode.SrcOver };
  14. private SKPaint HighQualityResizePaint { get; } = new SKPaint() { FilterQuality = SKFilterQuality.High };
  15. public SurfaceRenderer(int width, int height)
  16. {
  17. FinalBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null);
  18. var imageInfo = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul, SKColorSpace.CreateSrgb());
  19. BackingSurface = SKSurface.Create(imageInfo, FinalBitmap.BackBuffer, FinalBitmap.BackBufferStride);
  20. }
  21. public void Dispose()
  22. {
  23. BackingSurface.Dispose();
  24. BlendingPaint.Dispose();
  25. HighQualityResizePaint.Dispose();
  26. }
  27. public void Draw(Surface otherSurface, byte opacity)
  28. {
  29. Draw(otherSurface, opacity, new SKRectI(0, 0, otherSurface.Width, otherSurface.Height));
  30. }
  31. public void Draw(Surface otherSurface, byte opacity, SKRectI drawRect)
  32. {
  33. BackingSurface.Canvas.Clear();
  34. FinalBitmap.Lock();
  35. BlendingPaint.Color = new SKColor(255, 255, 255, opacity);
  36. using (var snapshot = otherSurface.SkiaSurface.Snapshot(drawRect))
  37. BackingSurface.Canvas.DrawImage(snapshot, new SKRect(0, 0, FinalBitmap.PixelWidth, FinalBitmap.PixelHeight), HighQualityResizePaint);
  38. FinalBitmap.AddDirtyRect(new Int32Rect(0, 0, FinalBitmap.PixelWidth, FinalBitmap.PixelHeight));
  39. FinalBitmap.Unlock();
  40. }
  41. }
  42. }