79723171

Date: 2025-08-02 06:48:03
Score: 1
Natty:
Report link

(Sorry if this post is useless, but in case it does help somebody I wanted to post.)

The answer put me on the right path. I wanted to resize the RectTransform of an image so that the size of the RT was close to the size of the rendered image (so only the image area was noticed by OnPointerClick). This StackOverflow post helped me size the width of the RT to the image, and I used a cross-multiply and divide to change the height when needed.

//getting the image
Image img = selectionRectTran.img;

//the initial/base size of the RT, resetting to it here
img.GetComponent<RectTransform>().sizeDelta = initialWidthHeightForSelectionImg;

float width = 0f;
float height = initialWidthHeightForSelectionImg.y; //default height


width = RectTranUtils.GetDesiredWidth(img); //from https://stackoverflow.com/questions/65385248/unity-get-the-actual-rendered-sprite-height-in-image-ui
width = Mathf.Clamp(width, 0f, img.GetComponent<RectTransform>().sizeDelta.x);

Debug.Log($"width diff: {Mathf.Abs(width - initialWidthHeightForSelectionImg.x)}");

//if the image is as wide as possible (ie, basically 0 diff between width between width and the default width)
//and the sprite - in pixels - is wider than it is tall, so there's some unwanted bounding box space on top and below the image
if (Mathf.Abs(width - initialWidthHeightForSelectionImg.x) < GameManager.TinyAmount 
    && img.sprite.texture.width > img.sprite.texture.height)
{
    //h = width * height of image in pixels / width of image in pixels
    height = width * img.sprite.texture.height / img.sprite.texture.width;
}

img.GetComponent<RectTransform>().sizeDelta = new Vector2(width, height);
        
Reasons:
  • Blacklisted phrase (1): StackOverflow
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Smerf