Unity www动态加载网上图片

一.

1.新建一个UGUI的Button,删掉它的Image组件,添加一个Raw Image组件.如图:

 由于删除了Image组件,所以画圈的位置是空的,运行后会自动把Raw Image添加到那里.

 

2.新建一个脚本挂到Button上.

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.UI;
 4 public class ButtonClickTest : MonoBehaviour
 5 {
 6     // 图片的地址 
 7     string url = "http://img.netbian.com/file/2017/0512/312be0e5cae93d373d362d589f434215.jpg";
 8     RawImage _Image; // 初始化组件
 9     IEnumerator Start() // 协程
10     {
11         WWW www = new WWW(url);
12         yield return www;
13         _Image = transform.GetComponent<RawImage>();
14         _Image.texture = www.texture;
15     }
16 }

3.运行.

 

二.

1.新建一个Button.

2.新建一个脚本挂在Button上.

 

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.UI;
 4 public class ButtonClickTest : MonoBehaviour
 5 {
 6     // 图片的地址 
 7     string url = "http://img.netbian.com/file/2017/0512/312be0e5cae93d373d362d589f434215.jpg";
 8     Image image; // 初始化组件
 9     IEnumerator Start() // 协程
10     {
11         WWW www = new WWW(url);
12         yield return www;
13         image = transform.GetComponent<Image>();
14 
15         if (www != null && string.IsNullOrEmpty(www.error))
16         {
17             //获取Texture
18             Texture2D texture = www.texture;
19 
20             //Texture转成Sprite(动态加载的图片一般是Texture类型的),但是这种转换方式很消耗资源,多了的话非常卡。
21             Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
22 
23             image.sprite = sprite;
24         }
25     }
26 }

3.运行.

 

posted @ 2017-11-06 16:15  朋丶Peng  阅读(1674)  评论(0编辑  收藏  举报