Tools for calculating aspect ratios
Calculates the aspect ratio from the provided width and height.
Automatically adjusts the width or height based on the provided ratio.
To find the aspect ratio, the key is to find the GCD (Greatest Common Divisor).
This can be done with a simple recursive function:
export const calculateGcd = (a: number, b: number): number =>
b === 0 ? a : calculateGcd(b, a % b);
Next, the GCD can be used to calculate the ratio:
const calculateAspectRatio = (width: number, height: number): string => {
const gcd = calculateGcd(width, height);
const x = width / gcd;
const y = height / gcd;
return `${x}:${y}`;
};