Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save liesislukas/62196813bbd871757796 to your computer and use it in GitHub Desktop.
Save liesislukas/62196813bbd871757796 to your computer and use it in GitHub Desktop.
static getSizeInContainer(item_x, item_y, container_x, container_y) {
/* euclidean GCD (feel free to use any other) */
function gcd(a, b) {
if (b > a) {
temp = a;
a = b;
b = temp
}
while (b != 0) {
m = a % b;
a = b;
b = m;
}
return a;
}
/* ratio is to get the gcd and divide each component by the gcd, then return a string with the typical colon-separated value */
function ratio(x, y) {
c = gcd(x, y);
var _x = (x / c);
var _y = (y / c);
return {
x: _x,
y: _y
};
}
var item_aspect = ratio(item_x, item_y);
if (!container_x) {
// default value
container_x = Dimensions.get('window').width * PixelRatio.get();
}
if (!container_y) {
// default value
container_y = Dimensions.get('window').height * PixelRatio.get();
}
var container_aspect = ratio(container_x, container_y);
var new_item_x = null;
var new_item_y = null;
// which way (x or y) will be maxed
if ((item_aspect.x / item_aspect.y) > (container_aspect.x / container_aspect.y)) {
// x will be maxed and we will have some extra space on y axe
new_item_x = container_x;
new_item_y = (new_item_x * item_aspect.y) / item_aspect.x;
} else {
// y will be maxed and we will have some extra space on x axe
new_item_y = container_y;
new_item_x = (new_item_y * item_aspect.x) / item_aspect.y;
}
return {
x: new_item_x,
y: new_item_y,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment