美文网首页
Unity 加载本地图片

Unity 加载本地图片

作者: 114105lijia | 来源:发表于2023-01-03 15:27 被阅读0次
一、使用File读取
void LocalBtyeToImage(Image image, string url) {

        if (!File.Exists(url))
            return;
   
        byte[] readBtye = File.ReadAllBytes(url);

        int width = Screen.width;
        int height = Screen.height;

        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(readBtye);

        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, width, height),
            new Vector2(0.5f, 0.5f));
        image.sprite = sprite;
    }
二、使用UnityWebRequest获取
IEnumerator FetchLocalPicture(Image image, string url) {

        if (!File.Exists(url)) 
            yield break;

        var uri = new System.Uri(Path.Combine(url));

        using (UnityWebRequest uwr = UnityWebRequest.Get(uri)) {
            DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
            uwr.downloadHandler = downloadHandlerTexture;

            yield return uwr.SendWebRequest();

            if (uwr.result == UnityWebRequest.Result.Success)
            {
                int width = Screen.width;
                int height = Screen.height;
                Texture2D texture = new Texture2D(width, height);
                texture = downloadHandlerTexture.texture;

                Sprite sprite = Sprite.Create(texture,
                    new Rect(0, 0, width, height),
                    new Vector2(0.5f, 0.5f));
                image.sprite = sprite;

                Resources.UnloadUnusedAssets();
            }
        }
    }

相关文章

网友评论

      本文标题:Unity 加载本地图片

      本文链接:https://www.haomeiwen.com/subject/akzhcdtx.html