Last active
August 29, 2015 14:12
-
-
Save ivan-kleshnin/9f63a8d3306efc046157 to your computer and use it in GitHub Desktop.
Resize with lwip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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