How do I size a UI Image to fit the sprite exactly?

I’m trying to size a UI Image to match the sprite dimensions exactly. If this was a SpriteRenderer, I would just drag the sprite onto the game object hierarchy, and it would be sized correctly automatically. however this is not possible using a UI Image. I tried doing things via script, but the units the rect transform uses are different than the units used by the SpriteRenderer and the sprite. Please Help!

Ok, Ill answer my own question. There is a “set native size” in the inspector for the image script. This will set the Rect Transform such that it fits the size of the sprite exactly. However, this does different things depending on the reference resolution of the Canvas scaler. Still not sure exactly how this works.

Answering this for people to come later

private Image myImage;
myImage.SetNativeSize();

In case anyone in the future has the same problem I did, you can also try changing the width and height of the UI image to match the sprite’s.

Hello!
I have exactly the same problem. Did anyone get a suggestion?

Best Regards,
James
MyACUVUE Rewards

Here’s the Fix for the Item Icon Scaling for UGUI Images (for an inventory system or whatever)

You can achieve uniform scaling by following these three steps.

(Note that I am assuming that you guys are making an inventory UI system)

1. Enable Preserve Aspect

If you hierarchy looks like this:

Slot 0 (parent)
└── Item (child)

Components the above hierarchy has:
Slot 0: Image component
Item: Image component

First, to ensure that the Item image doesn’t stretch awkwardly. On the Image component for your item icon, check the Preserve Aspect box.


2. Add This Component

To make the item fit perfectly inside the Slot parent’s bounds, add an Aspect Ratio Fitter component to the Item GameObject. Set the “Aspect Mode” to Fit In Parent.

image


3. Fixing Uniform Sizes

If your icons still appear at varying sizes (as seen below) and you want them to look uniform regardless of the original sprite dimensions:

Then go ahead and follow the detailed solution for matching the visual scale in this community discussion:

UI Image Icons Appear Different Sizes Despite Matching Visual Scale

In this discussion I talk about how to make the icons appear at the same size like this: