- Home /
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!
Answer by rodeowild · Jun 07, 2017 at 01:38 PM
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.
Just make sure "PixelsPerUnit" in sprite import match "Reference Pixels Per Unit" in canvas scaler and you should be good.
Also I just realized this post is from year and a half ago, but whatever
Something important which was tripping me up: Most people will be using prefabs.
"Set Native Size", as you mention, will size the image relative to the CanvasScaler.
For this reason, it's best to press the set native size button within the context, then apply changes to the prefab. It does weird things when I'm editing the prefab directly.
Answer by ImLife · Oct 14, 2019 at 11:22 PM
Answering this for people to come later
private Image myImage;
myImage.SetNativeSize();
Thanks! This solved my problem. The people of the future thank you.
– Person from the future
Your answer
Follow this Question
Related Questions
Angled UI image creates pixels ladder 1 Answer
Unity UI constant physical size one image 0 Answers
Is there a way to see if a sprite is sliced in code? 1 Answer
Show gameobject as part of UI 1 Answer
Best practice to display an icon 0 Answers