Set UI Image size to a Rectangle Unity3D

Viewed 506

I want to change the size of an UI image to match exactly the size of a rectangle that I create in real time, I tried the code below but the image is not aligned with the rectangle as you can see in the screenshot. How can I fix that?

Script:

public Image MyImage;

void Update () {

    Rect boundsDown = new Rect(0, Screen.height / 35, Screen.width / 1.05f, Screen.height /3);
    MyImage.rectTransform.sizeDelta = new Vector2(Screen.width / 1.1f, Screen.height / 3);
    MyImage.transform.position = boundsDown.position;
}

This is the result:

enter image description here

1 Answers

Probably your best bet here is to set the Image as a child of the rectangle, then set it to 100% of its parent element's width and height. Manually setting absolute values like you're attempting to do is somewhat britttle and won't handle things like changes in screen size.

public Image MyImage;
public RectTransform ParentRect;

void Update()
{
    MyImage.transform.parent = ParentRect.transform;
    MyImage.rectTransform.anchorMin = new Vector2(0f, 0f);
    MyImage.rectTransform.anchorMax = new Vector2(1f, 1f);
    MyImage.rectTransform.localPosition = new Vector3(0f, 0f, 0f);
}
Related