Fit an image to a specific board/screen

Spread the love

To fit an image to a screen we need to calculate the dimensions first. On browsers it’s easy to do, because they calculate in internally, but on to react native, then we have to calculate the size. The following code will help you to achieve that.

const transformImageSizeToContain = (
  boardToFitInto: {
    width: number;
    height: number;
  }, // screen size to fit into.
  boardTofit: {width: number; height: number}, // image to fit.
  strech?: boolean, // should stretch if image size is less than screen.
) => {
  const renderedImageDimentions = {width: 0, height: 0};
  const boardAndImageOrgWidthRatio = boardToFitInto.width / boardTofit.width;
  const boardAndImageOrgHeightRatio = boardToFitInto.height / boardTofit.height;

  if (
    boardTofit.width > boardToFitInto.width ||
    boardTofit.height > boardToFitInto.height
  ) {
    // image rescaled.
    if (boardAndImageOrgWidthRatio < boardAndImageOrgHeightRatio) {
      // width will be equal to board width
      renderedImageDimentions.width = boardToFitInto.width;
      renderedImageDimentions.height =
        boardTofit.height * (boardToFitInto.width / boardTofit.width);
    } else if (boardAndImageOrgWidthRatio > boardAndImageOrgHeightRatio) {
      // height will be equal to board height
      renderedImageDimentions.width =
        boardTofit.width * (boardToFitInto.height / boardTofit.height);
      renderedImageDimentions.height = boardToFitInto.height;
    } else {
      renderedImageDimentions.width = boardToFitInto.width;
      renderedImageDimentions.height = boardToFitInto.height;
    }
  } else {
    if (strech) {
      // Scale image to fit in the board.
      const ratio = Math.min(
        boardAndImageOrgWidthRatio,
        boardAndImageOrgHeightRatio,
      );
      renderedImageDimentions.width = boardTofit.width * ratio;
      renderedImageDimentions.height = boardTofit.height * ratio;
    } else {
      // Image not scaled and redendered as it is.
      renderedImageDimentions.width = boardTofit.width;
      renderedImageDimentions.height = boardTofit.height;
    }
  }
  return renderedImageDimentions;
};

Cheers and Peace out!!!