getCropRect method

Rect? getCropRect(
  1. Rect viewportCropRect
)

Calculates the crop rectangle in the ORIGINAL IMAGE coordinates.

Implementation

Rect? getCropRect(Rect viewportCropRect) {
  final Matrix4 transform = transformationController.value;
  final Matrix4 inverse = Matrix4.tryInvert(transform) ?? Matrix4.identity();

  // Map the view's crop rect (e.g. the circle center screen) back to the image element's local space
  final Offset topLeft = MatrixUtils.transformPoint(
    inverse,
    viewportCropRect.topLeft,
  );
  final Offset bottomRight = MatrixUtils.transformPoint(
    inverse,
    viewportCropRect.bottomRight,
  );
  final Rect localCropRect = Rect.fromPoints(topLeft, bottomRight);

  // Convert from "Rendered" size to "Original" size
  final double scaleX = _originalImage.width / _imageRenderSize.width;
  final double scaleY = _originalImage.height / _imageRenderSize.height;

  final Rect result = Rect.fromLTWH(
    localCropRect.left * scaleX,
    localCropRect.top * scaleY,
    localCropRect.width * scaleX,
    localCropRect.height * scaleY,
  );

  // Bounds check
  final Rect imageBounds = Rect.fromLTWH(
    0,
    0,
    _originalImage.width.toDouble(),
    _originalImage.height.toDouble(),
  );
  // Intersect to ensure we don't ask for pixels outside
  final Rect safeRect = result.intersect(imageBounds);

  if (safeRect.width <= 0 || safeRect.height <= 0) return null;

  return safeRect;
}