Constrained.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using QuestPDF.Drawing;
  3. using QuestPDF.Infrastructure;
  4. namespace QuestPDF.Elements
  5. {
  6. internal sealed class Constrained : ContainerElement, ICacheable, IContentDirectionAware
  7. {
  8. public ContentDirection ContentDirection { get; set; }
  9. public float? MinWidth { get; set; }
  10. public float? MaxWidth { get; set; }
  11. public float? MinHeight { get; set; }
  12. public float? MaxHeight { get; set; }
  13. internal override SpacePlan Measure(Size availableSpace)
  14. {
  15. if (MinWidth > availableSpace.Width + Size.Epsilon)
  16. return SpacePlan.Wrap();
  17. if (MinHeight > availableSpace.Height + Size.Epsilon)
  18. return SpacePlan.Wrap();
  19. var available = new Size(
  20. Min(MaxWidth, availableSpace.Width),
  21. Min(MaxHeight, availableSpace.Height));
  22. var measurement = base.Measure(available);
  23. if (measurement.Type == SpacePlanType.Wrap)
  24. return SpacePlan.Wrap();
  25. var actualSize = new Size(
  26. Max(MinWidth, measurement.Width),
  27. Max(MinHeight, measurement.Height));
  28. if (measurement.Type == SpacePlanType.FullRender)
  29. return SpacePlan.FullRender(actualSize);
  30. if (measurement.Type == SpacePlanType.PartialRender)
  31. return SpacePlan.PartialRender(actualSize);
  32. throw new NotSupportedException();
  33. }
  34. internal override void Draw(Size availableSpace)
  35. {
  36. var size = new Size(
  37. Min(MaxWidth, availableSpace.Width),
  38. Min(MaxHeight, availableSpace.Height));
  39. var offset = ContentDirection == ContentDirection.LeftToRight
  40. ? Position.Zero
  41. : new Position(availableSpace.Width - size.Width, 0);
  42. Canvas.Translate(offset);
  43. base.Draw(size);
  44. Canvas.Translate(offset.Reverse());
  45. }
  46. private static float Min(float? x, float y)
  47. {
  48. return x.HasValue ? Math.Min(x.Value, y) : y;
  49. }
  50. private static float Max(float? x, float y)
  51. {
  52. return x.HasValue ? Math.Max(x.Value, y) : y;
  53. }
  54. }
  55. }