Skip to content

Instantly share code, notes, and snippets.

@nomyfan
Last active April 29, 2023 09:14
Show Gist options
  • Save nomyfan/a03bc867cff9f2671668a2e8d101cb47 to your computer and use it in GitHub Desktop.
Save nomyfan/a03bc867cff9f2671668a2e8d101cb47 to your computer and use it in GitHub Desktop.
Calculate a image size to fit different platforms
type Width = number;
type Height = number;
type AspectRatio = [Width, Height];
type LowerUpperBounds = [number, number];
function unreachable(): never {
throw new Error("unreachable!");
}
function calculate(width: number, height: number, options: { ratioRange: LowerUpperBounds }): AspectRatio {
const ratio = width / height;
const { ratioRange: [lowerBound, upperBound] } = options;
if(ratio >= lowerBound && ratio <= upperBound) {
return [width, height];
}
if(ratio < lowerBound) {
// 不满的条件只有竖图小于lowerBound,增加宽度即可,lowerBound * 高度 = 新宽度
const newWidth = Math.ceil(lowerBound * height);
return [newWidth, height];
}
if(ratio > upperBound) {
// 不满足的条件只有横图大于upperBound,增加高度即可,宽度 / upperBound = 新高度
const newHeight = Math.ceil(width / upperBound);
return [width, newHeight];
}
unreachable();
}
function calculateInstagram(width: number, height: number): AspectRatio {
return calculate(width, height, { ratioRange: [0.8, 1.91] });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment