示例: 创建一个Image组件,将以下代码挂载到Image组件上即可;
代码:
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class UnityWebRequestTest : MonoBehaviour
{
[SerializeField]
private string spriteUrl = "https://tse2-mm.cn.bing.net/th/id/OIP-C._7u77Dxc_qt8twaYXp4DawHaP4?pid=ImgDet&rs=1";
[SerializeField] private bool isSaveLocally = true;
void Start()
{
DownLoadSprite(spriteUrl);
}
private void DownLoadSprite(string url)
{
StartCoroutine(LoadSprite(url));
}
IEnumerator LoadSprite(string url)
{
UnityWebRequest unityWebRequest = new UnityWebRequest(url);
DownloadHandlerTexture texD1 = new DownloadHandlerTexture(true);
unityWebRequest.downloadHandler = texD1;
yield return unityWebRequest.SendWebRequest();
int width = 1920;
int high = 1080;
if (unityWebRequest.result!=UnityWebRequest.Result.ConnectionError)
{
Texture2D texture2D = new Texture2D(width, high);
texture2D = texD1.texture;
if (isSaveLocally)
{
SaveLocally(texture2D, "菠萝", ".png");
}
Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),
new Vector2(0.5f, 0.5f));
transform.GetComponent<Image>().sprite = sprite;
transform.GetComponent<Image>().SetNativeSize();
}
}
private void SaveLocally(Texture2D texture2D, string texName, string spriteType)
{
Byte[] bytes = texture2D.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/" + texName + spriteType, bytes);
}
private void OnApplicationQuit()
{
StopAllCoroutines();
}
}
|