Last active
November 16, 2018 00:52
-
-
Save njncalub/391425b48d2b807b09c3 to your computer and use it in GitHub Desktop.
Center a Titanium.UI.ImageView inside a parent Titanium.UI.View similar to a `background-size: cover;` in CSS.
This file contains hidden or 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
/** | |
* Center a Titanium.UI.ImageView inside a parent Titanium.UI.View | |
* similar to a `background-size: cover;` in CSS. | |
* | |
* Takes 3 parameters: imageRatio, parentView, and imageView | |
* | |
* imageRatio: | |
* an object with the ratio or actual dimension of the image to be placed in the ImageView. | |
* e.g. {width: 3, height: 2} | |
* | |
* parentView: | |
* an object that defines the container where the ImageView is placed. This sets the boundaries | |
* or clipping size for the ImageView. Can be a View or a simple object. | |
* e.g. {width: 500, height: 500} | |
* | |
* imageView: | |
* the ImageView object to be centered in a parent View. | |
* e.g. $.imgViewThumb | |
* | |
*/ | |
var centerImageView = function(imageRatio, parentView, imageView) { | |
var h1, w1, h2, w2, x1, x2; | |
h1 = parseFloat(parentView.height); | |
w1 = parseFloat(parentView.width); | |
h2 = parseFloat(imageView.height); | |
w2 = parseFloat(imageView.width); | |
if (imageRatio.width > imageRatio.height) { | |
h2 = h1; | |
w2 = (imageRatio.width * h2) / imageRatio.height; | |
} else { | |
w2 = w1; | |
h2 = (imageRatio.height * w2) / imageRatio.width; | |
} | |
x1 = -((w2 * 0.5) - (w1 * 0.5)); | |
x2 = -((h2 * 0.5) - (h1 * 0.5)); | |
imageView.height = h2; | |
imageView.width = w2; | |
imageView.left = x1; | |
imageView.top = x2; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment