[closed]how to match boxcollider2d size with image after preserv aspect?

Hi All,

How could i resize the boxcollider2d to match with the image rect after preserv aspect is enable?

rectTransform.rect of image returning whole rectagle, but i want the width and height of image after resizing.

42732-screen-shot-2015-03-17-at-124904-pm.png

I found my answer:

Hope anyone interested would get this help

void SetBoxCollider()
    {
        RectTransform itemRectTransform = this.gameObject.GetComponent<RectTransform>();
        // strech box collider
        BoxCollider2D itemBoxCollider2D =  itemRectTransform.gameObject.GetComponent<BoxCollider2D>();
        if (itemBoxCollider2D != null)
        {
            Image image = itemRectTransform.gameObject.GetComponent<Image>();

			if (image.preserveAspect) {
				
				var originalW = (int)(image.sprite.rect.width);
				var originalH = (int)(image.sprite.rect.height);

				var currentW = image.rectTransform.rect.width;
				var currentH = image.rectTransform.rect.height;

				var ratio = Mathf.Min (currentW / originalW, currentH / originalH);

				var newW = image.sprite.rect.width * ratio;
				var newH = image.sprite.rect.height * ratio;

				itemBoxCollider2D.size = new Vector2 (newW, newH);
			} else {

				itemBoxCollider2D.size = image.rectTransform.rect.size;

			}
        }
    }

43540-screen-shot-2015-03-30-at-35615-pm.png

Working solution!

THANK YOU SO MUCH! Have been looking for a solution to my problem for ages. Decided to tackle it today. And I’m happy I came across your post because it actually works!

Been wasting my time with collider.bounds and rendered.bounds to no avail.

Tkx again!

Working fine!

Thanks, it works!