Unity,我有一个需要保留长宽比的图像,我需要根据图像在屏幕上的呈现方式而不是Rect Transform值来获取图像的x位置和宽度。希望您能理解。如何获得x-pos和宽度?
注意:在这种情况下,我不需要使用宽高比设置和内容大小设置。我只需要这些值。
[.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位置(范围),您只需获得该位置即可获得将值加倍的大小。另外,如果图像的宽度大于高度,则需要添加其他情况