矩形Aが矩形Bに含まれるように位置を調整

2025年1月8日水曜日

C# WPF

記事のカテゴリー: C#、.NET 9、WPF

矩形Aを矩形Bの真ん中に置く

矩形rを矩形baseRectの真ん中に移動します。

ちなみに、矩形とは4つの角がすべて直角な四角形のことです。

C#:

  1. public static Rect Center(Rect baseRect, Rect r)
  2. {
  3. r.Location = new Point(
  4. baseRect.Left + (baseRect.Width - r.Width) / 2,
  5. baseRect.Top + (baseRect.Height - r.Height) / 2);
  6. return r;
  7. }

矩形Aが矩形Bに含まれるように位置を調整

矩形rが矩形containerの中に含まれていればOK、含まれていなければ含まれるまで最小限位置をずらします。

C#:

  1. public static Rect OffsetIfNotContains(Rect container, Rect r)
  2. {
  3. if (!container.Contains(r))
  4. {
  5. double offsetX = 0;
  6. double offsetY = 0;
  7. if (r.Width < container.Width)
  8. {
  9. if (r.Left < container.Left)
  10. {
  11. offsetX = container.Left - r.Left;
  12. }
  13. else if (r.Right > container.Right)
  14. {
  15. offsetX = container.Right - r.Right;
  16. }
  17. }
  18. if (r.Height < container.Height)
  19. {
  20. if (r.Top < container.Top)
  21. {
  22. offsetY = container.Top - r.Top;
  23. }
  24. else if (r.Bottom > container.Bottom)
  25. {
  26. offsetY = container.Bottom - r.Bottom;
  27. }
  28. }
  29. r.Offset(offsetX, offsetY);
  30. }
  31. return r;
  32. }