DrawingUtils.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Drawing;
  3. namespace MediaBrowser.Api.Drawing
  4. {
  5. public static class DrawingUtils
  6. {
  7. /// <summary>
  8. /// Resizes a set of dimensions
  9. /// </summary>
  10. public static Size Resize(int currentWidth, int currentHeight, int? width, int? height, int? maxWidth, int? maxHeight)
  11. {
  12. return Resize(new Size(currentWidth, currentHeight), width, height, maxWidth, maxHeight);
  13. }
  14. /// <summary>
  15. /// Resizes a set of dimensions
  16. /// </summary>
  17. /// <param name="size">The original size object</param>
  18. /// <param name="width">A new fixed width, if desired</param>
  19. /// <param name="height">A new fixed neight, if desired</param>
  20. /// <param name="maxWidth">A max fixed width, if desired</param>
  21. /// <param name="maxHeight">A max fixed height, if desired</param>
  22. /// <returns>A new size object</returns>
  23. public static Size Resize(Size size, int? width, int? height, int? maxWidth, int? maxHeight)
  24. {
  25. decimal newWidth = size.Width;
  26. decimal newHeight = size.Height;
  27. if (width.HasValue && height.HasValue)
  28. {
  29. newWidth = width.Value;
  30. newHeight = height.Value;
  31. }
  32. else if (height.HasValue)
  33. {
  34. newWidth = GetNewWidth(newHeight, newWidth, height.Value);
  35. newHeight = height.Value;
  36. }
  37. else if (width.HasValue)
  38. {
  39. newHeight = GetNewHeight(newHeight, newWidth, width.Value);
  40. newWidth = width.Value;
  41. }
  42. if (maxHeight.HasValue && maxHeight < newHeight)
  43. {
  44. newWidth = GetNewWidth(newHeight, newWidth, maxHeight.Value);
  45. newHeight = maxHeight.Value;
  46. }
  47. if (maxWidth.HasValue && maxWidth < newWidth)
  48. {
  49. newHeight = GetNewHeight(newHeight, newWidth, maxWidth.Value);
  50. newWidth = maxWidth.Value;
  51. }
  52. return new Size(Convert.ToInt32(newWidth), Convert.ToInt32(newHeight));
  53. }
  54. private static decimal GetNewWidth(decimal currentHeight, decimal currentWidth, int newHeight)
  55. {
  56. decimal scaleFactor = newHeight;
  57. scaleFactor /= currentHeight;
  58. scaleFactor *= currentWidth;
  59. return scaleFactor;
  60. }
  61. private static decimal GetNewHeight(decimal currentHeight, decimal currentWidth, int newWidth)
  62. {
  63. decimal scaleFactor = newWidth;
  64. scaleFactor /= currentWidth;
  65. scaleFactor *= currentHeight;
  66. return scaleFactor;
  67. }
  68. }
  69. }