I have a UI panel and it contains UI images, I want to make that every time when I create new instance of image, that instance had the anchor relative to image sprite. Image sprite size can change, and I know that I have to use RectTransform.anchorMax and RectTransform.anchorMin, but cannot find solution.

What it is

What I want
Here is my workaround.
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
public class SetAnchorsByImageCorners : MonoBehaviour
{
[MenuItem ("CONTEXT/RectTransform/Set Anchor by corners")]
static void SetAnchor (MenuCommand command)
{
var rt = command.context.GetComponent<RectTransform>();
var rtParent = command.context.GetComponent<RectTransform>().parent.GetComponent<RectTransform>();
Vector3[] rtCorners = new Vector3[4];
Vector3[] rtParentCorners = new Vector3[4];
rt.GetWorldCorners(rtCorners);
rtParent.GetWorldCorners(rtParentCorners);
var rtP1 = rtCorners[0];
var rtP2 = rtCorners[2];
var rtParentP1 = rtParentCorners[0];
var rtParentP2 = rtParentCorners[2];
rtP1 = rtP1 - rtParentP1;
rtP2 = rtP2 - rtParentP1;
rtParentP2 = rtParentP2 - rtParentP1;
rtParentP1 = Vector3.zero;
var min = new Vector2(rtP1.x / rtParentP2.x, rtP1.y / rtParentP2.y);
var max = new Vector2(rtP2.x / rtParentP2.x, rtP2.y / rtParentP2.y);
rt.anchorMin = min;
rt.anchorMax = max;
rt.sizeDelta = Vector3.zero;
rt.anchoredPosition = Vector2.zero;
}
}
@Developer061 You saved my time by million hours! Gracias!
Sorry to say but you have to do it manually for each sprite,
The proper way is
- to reset the rect transfrom of the UI Image and
- press the setNative button, it will be centered with the original size of the sprite
- Set the Anchors manually
Btw it can be set to the anchors of the Parent by from the inpector
I need the same thing and “sorry to say Unity sucks” doesn’t work for me - the worse thing if you try to do a code for this changing anchor position will change image/sprite position too…
Here’s how much code you need to perform this function. You can create some editor addon or just like me use [ExecuteInEditMode] select your target and run this exact script on it.
RectTransform rt = target.GetComponent<RectTransform>();
Vector2 pos = rt.transform.position,
size = new Vector2(rt.rect.width, rt.rect.height)/2,
pos1 = pos - size, pos2 = pos + size;
rt.anchorMin = new Vector2(pos1.x / Screen.width, pos1.y / Screen.height);
rt.anchorMax = new Vector2(pos2.x / Screen.width, pos2.y / Screen.height);
rt.anchoredPosition = new Vector2(0, 0);
rt.sizeDelta = new Vector2(0, 0);