Unity_ngui_从网络获取图片资源

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);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值