码迷,mamicode.com
首页 > 其他好文 > 详细

UGUI 加载图片

时间:2015-01-28 12:55:23      阅读:715      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

图片是动态加载的,然后转换为sprite赋值到ugui的按钮上

代码如下

using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;

public class UITexLoader : MonoBehaviour 
{

    public string texname;
    private Texture2D m_Tex;
   

   
    private void LoadFromFile(string path)
    {
        m_Tex = new Texture2D(1, 1);
        m_Tex.LoadImage(ReadPNG(path));
    }

    private byte[] ReadPNG(string path)
    {
        FileStream fileStream = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read);

        fileStream.Seek(0, SeekOrigin.Begin);

        byte[] binary = new byte[fileStream.Length]; //创建文件长度的buffer
        fileStream.Read(binary, 0, (int)fileStream.Length);

        fileStream.Close();

        fileStream.Dispose();

        fileStream = null;

        return binary;
    }


    // Use this for initialization
    void Start()
    {
        
        LoadFromFile(texname);
        Sprite tempSprite = new Sprite();
        tempSprite = Sprite.Create(m_Tex, new Rect(0, 0, m_Tex.width, m_Tex.height), new Vector2(0, 0));
        GetComponent<Image>().sprite  =tempSprite;
    }
	
	// Update is called once per frame
	void Update ()
    {
	
	}
}

 把这个脚本绑定到UGUI的按钮上面,运行就可以把按钮上的图片 动态改变了 

UGUI 加载图片

标签:

原文地址:http://www.cnblogs.com/dragon2012/p/4255336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!