Unity 加载本地图片

一、使用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();
            }
        }
    }
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花