1.引用命名空间
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019111911085179.png)
2.首先定义变量
public string _Path = "Assets/Textures/Logo/";
public string _texname = "nike.png";
private Texture2D m_Tex;
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191119112102301.png)
3.然后在Start里找到需要给贴图的image
Logo = GameObject.Find("Logo").GetComponent();
![Logo = GameObject.Find("Logo").GetComponent();](https://img-blog.csdnimg.cn/20191119111136408.png)
4.定义两个方法(核心内容)
private void LoadFromFile(string path, string _name)
{
m_Tex = new Texture2D(1, 1);
m_Tex.LoadImage(ReadPNG(path + _name));
}
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;
}
5.准备工作全部完成了
可以开动啦
//加载
LoadFromFile(_Path, _texname);
//变换格式
Sprite tempSprite = Sprite.Create(m_Tex, new Rect(0, 0, m_Tex.width, m_Tex.height), new Vector2(10, 10));
Logo.sprite = tempSprite;//赋值
好了现在图片“nike.png”已经显示UI“Logo”上了。 快动手试试吧~。![在这里插入图片描述](https://img-blog.csdnimg.cn/20200114151229684.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAyMzMyOA==,size_16,color_FFFFFF,t_70)
如果想了解网络加载的小问号往下看, unity2018版本之后推出了用于替代www加载方式的方法"UnityWebRequest" 可以从网络链接加载图片资源并给到UI上,点击下方链接跳转文章:https://blog.csdn.net/weixin_45023328/article/details/106192943
|