UI Image: Using Sprite's pivot on the RectTransform

I’m creating a game, where I load sprites to UI Images on a canvas. When placing a UI Image, I need to set the pivot of it’s RectTransform, so it matches the pivot of the sprite.

It seems like an obvious thing to do, but I can’t get it to work.

Is that somehow possible?

I tried the following, with little luck:

	GetComponent<RectTransform> ().pivot = GetComponent<Image> ().sprite.pivot;

Any help is most welcome :slight_smile:

Sometimes your sprite has also custom value of pixels per unit set. In that case you do:

Vector2 size = imgObj.GetComponent<RectTransform>().sizeDelta;
size *= imgObj.GetComponent<Image>().pixelsPerUnit;
Vector2 pixelPivot = imgObj.GetComponent<Image>().sprite.pivot;
Vector2 percentPivot = new Vector2(pixelPivot.x / size.x, pixelPivot.y / size.y);
imgObj.GetComponent<RectTransform>().pivot = percentPivot;

Sprite.pivot info is by pixel, no percentage, which UI RectTransform uses.
This is the script I use to do this conversion.

Vector2 size = GetComponent&ltRectTransform&gt().sizeDelta;
Vector2 pixelPivot = GetComponent&ltImage&gt().sprite.pivot;
Vector2 percentPivot = new Vector2(pixelPivot.x / size.x, pixelPivot.y / size.y);
GetComponent&ltRectTransform&gt().pivot = percentPivot;

I know it’s an old answer but here is a one liner:

yourRectTransform.pivot = yourSprite.pivot / yourSprite.rect.size;

@TobyKaos 's answer is close but the pivot returned by the sprite is in pixels, and rectTransform’s is in “normalized” form i.e. expressed as a fraction of the total width/height of the

I think you should do:

myObject.GetComponent<RectTransform>().pivot = new Vector2(myObject.GetComponent<Image>().sprite.pivot);

It is like when you want to set a new position you must create a new Vector3. Here a Vector2