Thickness.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Linq;
  3. namespace MonoGame.Extended
  4. {
  5. public struct Thickness : IEquatable<Thickness>
  6. {
  7. public Thickness(int all)
  8. : this(all, all, all, all)
  9. {
  10. }
  11. public Thickness(int leftRight, int topBottom)
  12. : this(leftRight, topBottom, leftRight, topBottom)
  13. {
  14. }
  15. public Thickness(int left, int top, int right, int bottom)
  16. : this()
  17. {
  18. Left = left;
  19. Top = top;
  20. Right = right;
  21. Bottom = bottom;
  22. }
  23. public int Left { get; set; }
  24. public int Top { get; set; }
  25. public int Right { get; set; }
  26. public int Bottom { get; set; }
  27. public int Width => Left + Right;
  28. public int Height => Top + Bottom;
  29. public Size Size => new Size(Width, Height);
  30. public static implicit operator Thickness(int value)
  31. {
  32. return new Thickness(value);
  33. }
  34. public override bool Equals(object obj)
  35. {
  36. if (obj is Thickness)
  37. {
  38. var other = (Thickness)obj;
  39. return Equals(other);
  40. }
  41. return base.Equals(obj);
  42. }
  43. public override int GetHashCode()
  44. {
  45. unchecked
  46. {
  47. var hashCode = Left;
  48. hashCode = (hashCode * 397) ^ Top;
  49. hashCode = (hashCode * 397) ^ Right;
  50. hashCode = (hashCode * 397) ^ Bottom;
  51. return hashCode;
  52. }
  53. }
  54. public bool Equals(Thickness other)
  55. {
  56. return Left == other.Left && Right == other.Right && Top == other.Top && Bottom == other.Bottom;
  57. }
  58. public static Thickness FromValues(int[] values)
  59. {
  60. switch (values.Length)
  61. {
  62. case 1:
  63. return new Thickness(values[0]);
  64. case 2:
  65. return new Thickness(values[0], values[1]);
  66. case 4:
  67. return new Thickness(values[0], values[1], values[2], values[3]);
  68. default:
  69. throw new FormatException("Invalid thickness");
  70. }
  71. }
  72. public static Thickness Parse(string value)
  73. {
  74. var values = value
  75. .Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
  76. .Select(int.Parse)
  77. .ToArray();
  78. return FromValues(values);
  79. }
  80. public void Deconstruct(out int top, out int right, out int bottom, out int left) =>
  81. (top, right, bottom, left) = (Top, Right, Bottom, Left);
  82. public override string ToString()
  83. {
  84. if (Left == Right && Top == Bottom)
  85. return Left == Top ? $"{Left}" : $"{Left} {Top}";
  86. return $"{Left}, {Right}, {Top}, {Bottom}";
  87. }
  88. }
  89. }