Unity 网络图片加载
目录
OK 老规矩,直接上代码:
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEditor;
/// <summary>
/// 网络图片加载
/// </summary>
enum GetPicType
{
DownLoad = 0,
LocalLoad,
}
public class Picture : MonoBehaviour
{
//URL
string _URL = "http://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=3987907653,720009510&os=3586525006,165335113&simid=4093363352,542483519&pn=1&rn=1&di=212190&ln=768&fr=&fmq=1567676261198_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2Fc%2F53cdd1f7c1f21.jpg&rpstart=0&rpnum=0&adpicid=0&force=undefined";
/// <summary>
/// 网络下载的图片
/// </summary>
private Texture2D _Img = null;
/// <summary>
/// 本地图片
/// </summary>
private Texture2D _Img2 = null;
private bool _DownloadOK = false;
void OnGUI()
{
if (this._Img != null)
GUI.DrawTexture(new Rect(0, 0, 200, 300), this._Img);
if (this._Img2 != null)
GUI.DrawTexture(new Rect(320, 0, 200, 300), this._Img2);
if (GUI.Button(new Rect(210, 0, 100, 20), "显示网络图片"))
{
StartCoroutine(this.DownLoadTexture(this._URL, GetPicType.DownLoad));
}
if (GUI.Button(new Rect(210, 50, 100, 20), "显示本地图片"))
{
if (this._DownloadOK)
{
StartCoroutine(DownLoadTexture("file://" + Application.streamingAssetsPath + "/1.png", GetPicType.LocalLoad));
}
else
{
Debug.LogError("没有下载完毕");
}
}
}
IEnumerator DownLoadTexture(string _Url, GetPicType _GetType)
{
WWW _Web = new WWW(_Url);
Texture2D _TempImage;
yield return _Web;
if (_Web.isDone && _Web.error == null)
{
switch (_GetType)
{
case GetPicType.DownLoad:
{
this._Img = _Web.texture;
_TempImage = this._Img;
Debug.Log(_TempImage.width + " " + _TempImage.height);
break;
}
case GetPicType.LocalLoad:
this._Img2 = _Web.texture;
_TempImage = this._Img;
Debug.Log(_TempImage.width + " " + _TempImage.height);
break;
default:
_TempImage = null;
break;
}
if (_TempImage != null)
{
byte[] data = _TempImage.EncodeToPNG();
File.WriteAllBytes(Application.streamingAssetsPath + "/1.png", data);
this._DownloadOK = true;
}
}
}
}
暂时先这样吧,如果有时间的话就会更新,如果实在看不明白就留言,看到我会回复的。
路长远兮,与君共勉。