Unity 2D:获取渲染的UI图像的x轴和宽度,而不是rect变换的值

问题描述 投票:0回答:1

Unity,我有一个需要保留长宽比的图像,我需要根据图像在屏幕上的呈现方式而不是Rect Transform值来获取图像的x位置和宽度。希望您能理解。如何获得x-pos和宽度?

enter image description here

注意:在这种情况下,我不需要使用宽高比设置和内容大小设置。我只需要这些值。

unity3d user-interface canvas width rect
1个回答
0
投票

[.mainTexture.width将为您提供像素大小,并使用.pixelsPerUnit可以计算x位置(假设原点在中间)和宽度(单位)

忽略不位于原点处的偏移量。您的计算应如下所示:

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;

此计算应为您提供x位置(范围),您只需获得该位置即可获得将值加倍的大小。另外,如果图像的宽度大于高度,则需要添加其他情况

© www.soinside.com 2019 - 2024. All rights reserved.