I'm trying to use the new UI objects in Unity 4.6 to create a ranking screen where I download information about the users and show them. Among those informations I have an URL pointing to their picture.
Before the UI tools I was doing it with GUITexture and using the www.LoadImageIntoTexture method, but there doesn't seem to be a similar solution for UI Images. Using a GUITexture with a Rect Transform doesn't seem to work.
Should I just manually download the image and load it into the image or is there a similiar solution as with using WWW class?
The new Image component takes requires a sprite to render. What should work is download a PNG texture using the WWW class, then creating a sprite and finally assigning it to the component.
Here's some sample code.
See the pictures attached for actual results.
//This is the method you call if you use the "OnClick" event from a button click.
//We cannot call the Coroutine function below, because it breaks the rule for
//the event system. i.e. Must be a return type of void.
public void LoadImage () {
//Call the actual loading method
StartCoroutine(RealLoadImage());
}
//This is where the actual code is executed
private IEnumerator RealLoadImage () {
//A URL where the image is stored
string url = "http://www.axsu3d.com/DLs/AxSWP8Plugin/TileLogo.png";
//Call the WWW class constructor
WWW imageURLWWW = new WWW(url);
//Wait for the download
yield return imageURLWWW;
//Simple check to see if there's indeed a texture available
if(imageURLWWW.texture != null) {
//Construct a new Sprite
Sprite sprite = new Sprite();
//Create a new sprite using the Texture2D from the url.
//Note that the 400 parameter is the width and height.
//Adjust accordingly
sprite = Sprite.Create(imageURLWWW.texture, new Rect(0, 0, 400, 400), Vector2.zero);
//Assign the sprite to the Image Component
GetComponent<UnityEngine.UI.Image>().sprite = sprite;
}
yield return null;
}