Unity 在Image UI 中获取实际渲染的精灵高度

问题描述

我在 UI 上有一个图像,并且其精灵的“保留纵横比”为 True,因此根据附加到图像的精灵,精灵可能无法覆盖图像的所有矩形,我想要的是获取渲染精灵的真实高度,以便我可以将其应用于图像的矩形变换高度并使它们具有相同的高度

解决方法

您可以使用 rect 字段以像素为单位获取精灵高度 - 返回 Location of the Sprite on the original Texture,specified in pixels. 这意味着它也适用于 SpriteAtlas。

Vector2 size = myImage.sprite.rect.size;
//or
float width = myImage.sprite.rect.width;
float height = myImage.sprite.rect.height;