由于Image和Button的图片要求是Sprite类型的,当有大量图片时,一个一个的操作不方便,所以考虑动态的将jpg或png图片进行转换格式。
运行时,将Texture2D转换成Sprite格式
核心方式:WWW.LoadImageIntoTexture 加载图像到纹理
这里我用一个按钮来操作:
IEnumerator Load(string path) { WWW www = new WWW(path); yield return www; if (!string.IsNullOrEmpty(www.error)) { Debug.Log(www.error); } else{ if (www.isDone) { Texture2D tex = new Texture2D(64, 64); www.LoadImageIntoTexture(tex); Sprite sprite = Sprite.Create(tex, new Rect(0, 0, 64, 64), Vector2.zero); GameObject btngo = GameObject.Find(“Button”); if (btngo) { btngo.GetComponent().sprite = sprite; } } } }
调用:
StartCoroutine(Load("file://" + Application.persistentDataPath + "/Folder/File.jpg"));