Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Last active August 29, 2015 14:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-kleshnin/9f63a8d3306efc046157 to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/9f63a8d3306efc046157 to your computer and use it in GitHub Desktop.
Resize with lwip
// resolution is [width, height] structure
// Evaluate resolution by width (height doesn't matter, just keep it proportional)
function evalResolutionByWidth(requiredWidth, actualResolution) {
var actualWidth = actualResolution[0];
var actualHeight = actualResolution[1];
if (actualWidth > requiredWidth) {
var scale = actualWidth / requiredWidth;
return [requiredWidth, Math.round(actualHeight / scale)];
} else {
return actualResolution;
}
}
// Evaluate resolution by height (width doesn't matter, just keep it proportional)
function evalResolutionByHeight(requiredHeight, actualResolution) {
var actualWidth = actualResolution[0];
var actualHeight = actualResolution[1];
if (actualHeight > requiredHeight) {
var scale = actualHeight / requiredHeight;
return [Math.round(actualWidth / scale), requiredHeight];
} else {
return actualResolution;
}
}
// Like `image.contain` but without "black borders"
function evalResolution(requiredResolution, actualResolution) {
if (actualResolution[0] >= actualResolution[1]) {
// width >= height
if (actualResolution[0] > requiredResolution[0]) {
return evalResolutionByWidth(requiredResolution[0], actualResolution);
} else {
return actualResolution;
}
} else {
// height > width
if (actualResolution[1] > requiredResolution[1]) {
return evalResolutionByHeight(requiredResolution[1], actualResolution);
} else {
return actualResolution;
}
}
}
// You may use `.bind` for partial application. Just for example:
// exports.evalSmallResolution = evalResolutionByHeight.bind(null, SMALL_HEIGHT); // this = null, requiredHeight = SMALL_HEIGHT
// exports.evalMediumResolution = evalResolutionByHeight.bind(null, MEDIUM_HEIGHT); // this = null, requiredHeight = MEDIUM_HEIGHT
// exports.evalBigResolution = evalResolution.bind(null, [BIG_WIDTH, BIG_HEIGHT]); // this = null, requiredResolution = [BIG_WIDTH, BIG_HEIGHT]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment