Unity RectTransform resizing.

I have had some issues trying to resize a RectTransform with code.
I find it hard to explain, so here are some GIFs.

This is what I want:
timelyneardungenesscrab

This is what I have:
occasionalnippycavy

This is the code that I have:

public class ScaleableView : MonoBehaviour, IDragHandler
{
    private Canvas m_canvas;
    [SerializeField] private RectTransform m_rect;

    private void Awake()
    {
        m_canvas = GetComponentInParent<Canvas>();
    }

    public void OnDrag(PointerEventData eventData)
    {
        m_rect.offsetMin = eventData.position / m_canvas.scaleFactor;
    }
}

Probably the best way to do this is by changing the anchors. Anchors are in relative space to the objects parent. So, if you make sure that the parent of the window is as big as the screen you can calculate the desired anchor position like this:

float x = Input.mousePosition.x / Screen.width;
float y = Input.mousePosition.y / Screen.height;

Depending on the corner you are dragging, you have to assign x to anchorMin.x or anchorMax.x, and y to anchorMin.y or anchorMax.y.

Note that your pixel positions / sizes (anchoredPosition and sizeDelta) should be zero.

1 Like

Thank you so much, I figured out how to make it work using the anchoredMin/anchoredMax.
You saved my project :smile:

1 Like