- Home /
Possible to convert UnityEngine.2DTexture to UnityEngine.UI.Image?
I am getting the user's avatar from UnityEngine.Social using Google Play Service,
var byteArray = Social.localUser.image.EncodeToPNG();
The avatar is a 2DTexture which I could draw with GUI.DrawTexture(...) using the old style 'Rect's, but it would be a lot easier and cleaner if I could keep all my UI as gameobjects in nested canvases and have the avatar as a UI.Image. Is there a possible way to convert a 2DTexture to a UI.Image? I am trying to use ImageConversion.EncodeToPNG() which gives a byte[], but have not had any luck making the avatar a UI.Image. Please help!
Answer by JayGarxP · May 20, 2019 at 09:29 PM
Use Sprite.Create() to convert a 2dTexture into a Sprite using Rect() constructor; then set the created sprite as UnityEngine.UI.Image' Sprite component.
var avatar = Social.localUser.image;
Sprite sprite = Sprite.Create(avatar, new Rect(0, 0, avatar.width, avatar.height), new Vector2(.5f, .5f));
AvatarImage.sprite = sprite;
Your answer
Follow this Question
Related Questions
Get Image from another scene 2 Answers
Canvas with mask and transparent image 1 Answer
Why is my texture2D screenshot coming out as a grey box? 1 Answer
Convert UI element to world position 1 Answer