getContentRect method

Rect getContentRect()

Calculates the bounding rectangle of the content in the matrix.

This method finds the smallest rectangle that encompasses all true cells in the matrix. It's useful for determining the area of the matrix that contains actual content.

Returns: A Rect object representing the bounding rectangle of the content. The rectangle is defined by its left, top, right, and bottom coordinates.

If the matrix is empty or contains no true cells, it returns Rect.zero.

Note:

  • The returned Rect uses double values for coordinates to be compatible with Flutter's Rect class.
  • The right and bottom coordinates are exclusive (i.e., they point to the cell just after the last true cell in each direction).

Implementation

Rect getContentRect() {
  int minX = cols;
  int maxX = -1;
  int minY = rows;
  int maxY = -1;

  for (int y = 0; y < rows; y++) {
    for (int x = 0; x < cols; x++) {
      if (_data[y][x]) {
        minX = min(minX, x);
        maxX = max(maxX, x);
        minY = min(minY, y);
        maxY = max(maxY, y);
      }
    }
  }

  // If no content found, return Rect.zero
  if (maxX == -1 || maxY == -1) {
    return Rect.zero;
  } else {
    return Rect.fromLTRB(
      minX.toDouble(),
      minY.toDouble(),
      (maxX + 1).toDouble(),
      (maxY + 1).toDouble(),
    );
  }
}