1.创建ngui一个 ui 在plane下面添加一个空物体,然后在添加一个脚本uiTexure,
2.绑定一下代码。
using System;
using System.IO;
using System.Text;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
public class LoadWebImage : MonoBehaviour {
public string url;
private Texture texture;
private UIAtlas uiatlas;
// Use this for initialization
void Start () {
if(null !=url)
{
StartCoroutine(LoadImage(url));
}
}
IEnumerator LoadImage(string url){
bool exists = Exits(url);
if(exists)
{
url = "file:///"+Path(url);
Debug.Log("url---"+url);
}else
{
Debug.Log("load image from www:" + url);
}
WWW www = new WWW(url);
yield return www;
if(string.IsNullOrEmpty(www.error) )
{
SetTexture(www.texture);
if(!exists)
{
Save(www);
}
}
else
{
Debug.LogError("download image [url=" + www.url + "] error!" + www.error);
}
}
/// <summary>
/// 缓存的基础路径
/// </summary>
string BasePath
{
get
{
Debug.Log("Application--"+Application.persistentDataPath);
return Application.persistentDataPath + "/Images/";
}
}
/// <summary>
/// 获取缓存路径
/// </summary>
string Path(string url)
{
return BasePath +""+ url.Trim() + ".img";
}
/// <summary>
/// 检测缓存是否存在
/// </summary>
bool Exits(string url)
{
#if !UNITY_WEBPLAYER
return File.Exists(Path(url));
#else
return false;
#endif
}
/// <summary>
/// 保持图片
/// </summary>
void Save(WWW www)
{
#if !UNITY_WEBPLAYER
try
{
if (!Directory.Exists(BasePath))
{
Directory.CreateDirectory(BasePath);
}
File.WriteAllBytes(Path(www.url),www.bytes);
}
catch(Exception e)
{
}
#endif
}
/// <summary>
/// 填充纹理
/// </summary>
void SetTexture(Texture2D img)
{
//texture = img;
//GUI texture
if(guiTexture != null)
{
guiTexture.texture = img;
return;
}
//NGUI texture
UITexture texture = GetComponent<UITexture>();
if(texture != null)
{
texture.mainTexture = img;
return;
}
//NGUI sprite
// UISprite sprite = GetComponent<UISprite>();
// if(sprite != null)
// {
// img.name = "main";
// List<Texture> texs = new List<Texture>();
// texs.Add(img);
// uiatlas = new UIAtlas();
// //uiatlas.spriteList.Add = texs;
//
// sprite.atlas = uiatlas;
// sprite.spriteName = "main";
// return;
// }
}
void OnDestroy()
{
GameObject.Destroy(texture);
GameObject.Destroy(uiatlas);
}
}