Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Have an Unity UI Image.

I want to load a .PNG file that is in my persistent data path and use it as the sprite source for the UI Image. Code:

    byte[] bytes = File.ReadAllBytes(Application.persistentDataPath + "/sprite.png");
    Texture2D texture = new Texture2D(width, height);
    texture.filterMode = FilterMode.Trilinear;
    texture.LoadImage(bytes);
    Sprite sprite = Sprite.Create(texture, new Rect(0,0,width, height), new Vector2(0.5f,0.0f), 1.0f);

    myObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite;

This almost works. Only a portion of the image is displayed.

The initial guess would be that I didn't load the image properly. However, if you use a SpriteRenderer instead of UnityEngine.UI.Image like

    myObject.GetComponent<SpriteRenderer>().sprite = sprite;

The image is displayed in full. So this seems to be a problem with UnityEngine.UI.Image specifically...

... However, if you drag an image from the editor into the Sprite Source property of UnityEngine.UI.Image, then such image is displayed in full - then suggesting that there is something wrong with the way I load my image bytes.

What should I do?

Edit: If you set the image type to Tiled, you can see that it tiles with the full image... So apparently the UI Image component DOES have all the image data but for some reason it won't render all of it.

share|improve this question
    
When you create the sprite maybe width and height are wrong? Take it directly from the loaded texture. – JeanLuc Feb 14 '15 at 9:11
up vote 3 down vote accepted

I was experiencing this same issue where not all of the image was displaying.

I solved it by setting mipmap to false (last parameter):

Texture2D texture = new Texture2D(900, 900, TextureFormat.RGB24, false);

My image then displayed as per the source PNG file.

share|improve this answer

make sure that tye Image of your myObject is child of Canvas. I am guessing that you create the image on the fly or parent it to the myObject instead of Canvas.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.