首页 > 解决方案 > Unity 2D:获取渲染的 UI 图像的 x 轴和宽度,而不是矩形变换的值

问题描述

Unity,我有一个需要启用保留纵横比的图像,我需要根据它在屏幕中的呈现方式而不是 Rect Transform 值来获取图像的 x-pos 和宽度。我希望你理解可能有问题。我怎样才能得到这个的x-pos和宽度?

在此处输入图像描述

注意:对于这种情况,我不需要使用 Aspect Ratio Fitter 和 Content Size Fitter。我只需要这些价值观。

标签: unity3duser-interfacecanvaswidthrect

解决方案


.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 位置(范围),以获得您只需将值加倍的大小。此外,如果图像的宽度大于高度,您需要添加额外的案例


推荐阅读