unity3d - Unity 2D:获取渲染的 UI 图像的 x 轴和宽度,而不是矩形变换的值
问题描述
Unity,我有一个需要启用保留纵横比的图像,我需要根据它在屏幕中的呈现方式而不是 Rect Transform 值来获取图像的 x-pos 和宽度。我希望你理解可能有问题。我怎样才能得到这个的x-pos和宽度?
注意:对于这种情况,我不需要使用 Aspect Ratio Fitter 和 Content Size Fitter。我只需要这些价值观。
解决方案
.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 位置(范围),以获得您只需将值加倍的大小。此外,如果图像的宽度大于高度,您需要添加额外的案例
推荐阅读
- font-awesome-5 - 如何将 font-awesome sass 从 4.7 更新到 5.12.1
- c# - 在 WPF 中定位和覆盖图像的最佳方法是什么?
- sql - Oracle SQL 加载器 - 在同一列中加载不一致的日期格式
- postgresql - 如何检查驻留在内存(缓存数据)中的“实际数据记录”,例如 PostgreSQL 进程的共享、常驻和 RAM 内存位置?
- javascript - chrome.storage 项仅在重新加载页面 Chrome 扩展后更改
- c# - 在 RazorPage 中引用来自另一个项目的类
- linux - 在 docker 图像上使用 curl 而不是 wget
- c# - 如何在 C# 中转换 dateTime 格式?
- laravel - 如何像在 Provider 中注册路由一样,分别为所有模块注册 graphql?
- apache - 使 .htaccess 在符号链接目标文件夹中工作