How to scale sprites to fit to UI Image component in Unity

Viewed 24

I am trying to load an image from web and set it to UI Image component on canvas.

I set 100x100 width and height for UI Image but sprites downloaded from web arent not the same width/height so I would like to resize the sprite to fit in the Image component. Or I would like to set the width 100 for a sprite and set the height automatically to keep the sprite original ratio.

Does anyone know how to achieve this?

I use the script below to load from web and it sets original image size, ignoring UI Image component size.

public class LoadImageFromWeb : MonoBehaviour
{
    private Image image;

    void Start()
    {
        image = GetComponent<Image>();
        StartCoroutine(DownloadImage(url));
    }

    IEnumerator DownloadImage(string MediaUrl)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
        yield return request.SendWebRequest();

        if (request.result != UnityWebRequest.Result.Success)
            Debug.Log(request.error);
        else
        {
            Texture2D texture = DownloadHandlerTexture.GetContent(request);
            image.sprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), Vector2.zero);
            image.SetNativeSize();
        }
    }
}

I tried setting 100f in Create method like

Sprite.Create(texture, new Rect(0f, 0f, 100f, 100f), Vector2.zero)

but it just trims the image at the wrong position (the whole image not displayed).

I would appreciate any helps! thank you!

0 Answers
Related