unity 从本地文件夹获取图片并赋值给UI作为贴图
1.引用命名空间
2.首先定义变量
public string _Path = "Assets/Textures/Logo/";
public string _texname = "nike.png";
private Texture2D m_Tex;
3.然后在Start里找到需要给贴图的image
Logo = GameObject.Find("Logo").GetComponent<Image>();
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”上了。
快动手试试吧~。
如果想了解网络加载的小问号往下看,
unity2018版本之后推出了用于替代www加载方式的方法"UnityWebRequest"
可以从网络链接加载图片资源并给到UI上,点击下方链接跳转文章:https://blog.csdn.net/weixin_45023328/article/details/106192943