Reputation: 83
Unity, I have an image that need enable preserved aspect ratio and I need to get the x-pos & width of the image based on how it was rendered in the screen and NOT the Rect Transform values. I hope you understand may problem. How can I get the x-pos and width of this?
Note: I don't need to use Aspect Ratio Fitter and Content Size Fitter for this situation. I just need those values.
Upvotes: 2
Views: 1347
Reputation: 560
.mainTexture.width
will give you the pixelsize and with .pixelsPerUnit
you can calculate the x poition (assuming that origin in in the middle) and width in units
ignoring the offset that comes with not being at the origin. your calculation should be something like this:
float size = 0;
if ((float)img.sprite.texture.width / transform.GetComponent<RectTransform>().rect.width <
(float)img.sprite.texture.height / transform.GetComponent<RectTransform>().rect.height)
{
size = (img.sprite.texture.width * transform.GetComponent<RectTransform>().rect.height /(float) img.sprite.texture.height);
}
else
{
size = transform.GetComponent<RectTransform>().rect.width;
}
float x = size * img.pixelsPerUnit * transform.lossyScale.x;
this calculation should give you the x position (extent) you asked for to get the size you just need to double the value. Also if an image has a higher width then height you need to add additional cases
Upvotes: 0