unity 动态设置set native size
时间: 2023-12-22 16:06:30 浏览: 61
在 Unity 中,可以使用以下代码动态设置 Image 组件的 Native Size:
```csharp
// 获取 Image 组件
Image image = GetComponent<Image>();
// 设置 Image 组件的 sprite
image.sprite = yourSprite;
// 设置 Image 的 Preserve Aspect 为 true
image.preserveAspect = true;
// 设置 Image 的 Set Native Size 为 true
image.SetNativeSize();
```
这样就可以动态设置 Image 组件的 Native Size 了。需要注意的是,在设置 Native Size 前,要先设置 Image 的 sprite,并将 Preserve Aspect 设置为 true,否则设置 Native Size 可能会产生意想不到的效果。
相关问题
unity set native size跟原大小不一样
Unity的Set Native Size功能是将UI元素的大小设置为其原始图像的大小。但是,如果图像的分辨率与UI元素的分辨率不同,则Set Native Size将会根据UI元素的分辨率调整图像的大小,以使其填充整个UI元素。因此,如果您的UI元素的分辨率不同于原始图像的分辨率,则Set Native Size将会使它们的大小不同。要解决此问题,您可以手动调整UI元素的大小,以使其与原始图像的大小匹配。
public void ReplaceIMG(RawImage _rawImg, string path) { print("ReplaceIMGwww"); try { var tex = DownloadSync("file://" + path).texture; if (tex == null) return; tex.wrapMode = TextureWrapMode.Clamp; float width = tex.width; float height = tex.height; _rawImg.texture = tex; _rawImg.SetNativeSize(); tex = null; } catch (Exception e) { Debug.Log(e.Message); } } public static UnityWebRequest DownloadSync(string path, WWWForm form = null) { UnityWebRequest www; if (form != null) www = UnityWebRequest.Post(path, form); else www = UnityWebRequest.Get(path); www.SendWebRequest(); YieldToStop(www); return www; } private static void YieldToStop(UnityWebRequest www) { var @enum = DownloadEnumerator(www); while (@enum.MoveNext()) ; } private static IEnumerator DownloadEnumerator(UnityWebRequest www) { while (!www.isDone) { yield return null; } yield return www; }
这是一段 Unity3D 中用于替换图片的代码。其中 ReplaceIMG 函数接受一个 RawImage 和一个图片路径参数,会通过 DownloadSync 函数下载该路径下的图片,然后将其设置为 RawImage 的 texture。DownloadSync 函数使用 UnityWebRequest 发送一个 GET 或 POST 请求,然后通过 YieldToStop 函数阻塞协程,直到请求完成后返回 UnityWebRequest 对象。DownloadEnumerator 函数则是用于实现 YieldToStop 函数的协程函数,它会在请求完成前不断循环,每次循环等待一帧。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)