BitmapPixelChanges.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using PixiEditor.Helpers.Extensions;
  2. using PixiEditor.Models.Position;
  3. using SkiaSharp;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. namespace PixiEditor.Models.DataHolders
  8. {
  9. public struct BitmapPixelChanges
  10. {
  11. public BitmapPixelChanges(Dictionary<Coordinates, SKColor> changedPixels)
  12. {
  13. ChangedPixels = changedPixels;
  14. WasBuiltAsSingleColored = false;
  15. }
  16. public static BitmapPixelChanges Empty => new BitmapPixelChanges(new Dictionary<Coordinates, SKColor>());
  17. public bool WasBuiltAsSingleColored { get; private set; }
  18. public Dictionary<Coordinates, SKColor> ChangedPixels { get; set; }
  19. /// <summary>
  20. /// Builds BitmapPixelChanges with only one color for specified coordinates.
  21. /// </summary>
  22. /// <returns>Single-colored BitmapPixelChanges.</returns>
  23. public static BitmapPixelChanges FromSingleColoredArray(IEnumerable<Coordinates> coordinates, SKColor color)
  24. {
  25. Dictionary<Coordinates, SKColor> dict = new Dictionary<Coordinates, SKColor>();
  26. foreach (Coordinates coordinate in coordinates)
  27. {
  28. if (dict.ContainsKey(coordinate))
  29. {
  30. continue;
  31. }
  32. dict.Add(coordinate, color);
  33. }
  34. return new BitmapPixelChanges(dict) { WasBuiltAsSingleColored = true };
  35. }
  36. /// <summary>
  37. /// Combines pixel changes array with overriding values.
  38. /// </summary>
  39. /// <param name="changes">BitmapPixelChanges to combine.</param>
  40. /// <returns>Combined BitmapPixelChanges.</returns>
  41. public static BitmapPixelChanges CombineOverride(BitmapPixelChanges[] changes)
  42. {
  43. if (changes == null || changes.Length == 0)
  44. {
  45. throw new ArgumentException();
  46. }
  47. BitmapPixelChanges output = Empty;
  48. for (int i = 0; i < changes.Length; i++)
  49. {
  50. output.ChangedPixels.AddRangeOverride(changes[i].ChangedPixels);
  51. }
  52. return output;
  53. }
  54. public static BitmapPixelChanges CombineOverride(BitmapPixelChanges changes1, BitmapPixelChanges changes2)
  55. {
  56. return CombineOverride(new[] { changes1, changes2 });
  57. }
  58. public BitmapPixelChanges WithoutTransparentPixels()
  59. {
  60. return new BitmapPixelChanges(ChangedPixels.Where(x => x.Value.Alpha > 0).ToDictionary(y => y.Key, y => y.Value));
  61. }
  62. }
  63. }