clampedTo method

DiagramCameraState clampedTo(
  1. CanvasBounds canvas,
  2. DiagramRect? content
)

This camera with its center kept within canvas: the extent of content, or a viewport-sized canvas around the origin when there is none, with the canvas padding in viewport pixels around it.

Implementation

DiagramCameraState clampedTo(CanvasBounds canvas, DiagramRect? content) {
  final padding = switch (canvas) {
    InfiniteCanvasBounds() => null,
    FitCanvasBounds(:final padding) => padding,
  };
  if (padding == null) return this;
  final bounds =
      (content == null || content.width <= 0 || content.height <= 0
              ? DiagramRect.fromLTWH(
                  -viewportSize.width / zoom / 2,
                  -viewportSize.height / zoom / 2,
                  viewportSize.width / zoom,
                  viewportSize.height / zoom,
                )
              : content)
          .inflate(padding / zoom);
  final halfWidth = viewportSize.width / zoom / 2;
  final halfHeight = viewportSize.height / zoom / 2;
  final horizontalA = bounds.left + halfWidth;
  final horizontalB = bounds.right - halfWidth;
  final verticalA = bounds.top + halfHeight;
  final verticalB = bounds.bottom - halfHeight;
  final clamped = DiagramPoint(
    center.x.clamp(
      math.min(horizontalA, horizontalB),
      math.max(horizontalA, horizontalB),
    ),
    center.y.clamp(
      math.min(verticalA, verticalB),
      math.max(verticalA, verticalB),
    ),
  );
  return clamped == center ? this : copyWith(center: clamped);
}