clampToBounds function
MovaMiniRect
clampToBounds(
- MovaMiniRect r, {
- required MovaMiniRect bounds,
- required MovaMiniInsets insets,
- double margin = 0,
Clamps r so it lies fully inside bounds minus insets and margin.
Exposed separately because the drag itself needs it every frame, while
snapping only happens on release.
钳制 r 使其完全落在 bounds 去掉 insets 与 margin 后的区域内。
单独暴露是因为拖动过程每帧都要用它,而吸边只在松手时发生。
Implementation
MovaMiniRect clampToBounds(
MovaMiniRect r, {
required MovaMiniRect bounds,
required MovaMiniInsets insets,
double margin = 0,
}) {
final minLeft = bounds.left + insets.left + margin;
final maxRight = bounds.right - insets.right - margin;
final minTop = bounds.top + insets.top + margin;
final maxBottom = bounds.bottom - insets.bottom - margin;
// Floored at zero: insets/margin can exceed the raw bounds during a fast
// rotation or before the host's layout has settled, which would otherwise
// make `maxRight - minLeft` itself negative — and a negative `width`/
// `height` below trips Flutter's layout assertions instead of landing in
// the degenerate top-left fallback the comment further down promises.
//
// 下限钳到零:转屏过程中或宿主布局尚未稳定时,insets/margin 可能超过原始
// bounds,否则 `maxRight - minLeft` 本身就会算出负数——下面的负
// `width`/`height` 会触发 Flutter 的布局断言,而不是落进后面注释承诺的
// 那个退化左上对齐兜底。
final availableWidth = (maxRight - minLeft).clamp(0.0, double.infinity);
final availableHeight = (maxBottom - minTop).clamp(0.0, double.infinity);
// Degenerate case: the window is wider/taller than the available area.
// Fall back to top-left alignment instead of producing a negative width.
//
// 退化情形:窗口比可用区还大。退回左上对齐,而不是产生负宽/负高。
final width = r.width > availableWidth ? availableWidth : r.width;
final height = r.height > availableHeight ? availableHeight : r.height;
var left = r.left;
var top = r.top;
if (left < minLeft) left = minLeft;
final maxLeft = minLeft + (availableWidth - width);
if (left > maxLeft) left = maxLeft;
if (top < minTop) top = minTop;
final maxTop = minTop + (availableHeight - height);
if (top > maxTop) top = maxTop;
return MovaMiniRect(left: left, top: top, width: width, height: height);
}