sizeFromAspect function

Size sizeFromAspect({
  1. required String aspectRatio,
  2. double? width,
  3. double? height,
})

Calculates the size based on the aspect ratio and optional width and height.

If both width and height are provided, it returns a Size object with the specified width and height. If only width is provided, it calculates the height based on the aspect ratio and returns a Size object with the specified width and calculated height. If only height is provided, it calculates the width based on the aspect ratio and returns a Size object with the calculated width and specified height. If neither width nor height is provided, it returns a Size object based on the aspect ratio.

Throws an ArgumentError if the aspect ratio format is invalid.

  • aspectRatio: The aspect ratio in string format.
  • width: The optional width.
  • height: The optional height.

Returns a Size object representing the calculated size.

Implementation

Size sizeFromAspect({required String aspectRatio, double? width, double? height}) {
  if (width != null && height != null) {
    return Size(width, height);
  }

  Size size = aspectRatio.toSize;

  if (size.width <= 0 && size.height <= 0) {
    throw ArgumentError('Invalid aspect ratio format.');
  }

  if (width != null) {
    return Size(width, width / max(size.width, size.height) * min(size.width, size.height));
  } else if (height != null) {
    return Size(height / min(size.width, size.height) * max(size.width, size.height), height);
  } else {
    return size;
  }
}