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 ().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().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.
Answer
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.
No comments:
Post a Comment