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
myObject.GetComponent<SpriteRenderer>().sprite = sprite;
The image is displayed in full. So this seems to be a problem with
... 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.