【问题标题】:Unity Get the actual rendered sprite height in Image UIunity 获取Image UI中实际渲染的精灵高度
【发布时间】:2021-03-30 18:32:53
【问题描述】:

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

【问题讨论】:

    标签: image unity3d height sprite


    【解决方案1】:

    您可以使用 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;
    

    【讨论】:

    • 感谢您的评论!,我已经尝试过了,但它返回给我的高度与当前图像的高度相同:c
    【解决方案2】:

    我得到了解决方案,请记住,这适用于 Image 组件上允许的“保留方面”。此函数根据指定的宽度和图像上精灵的纹理大小获取所需的高度。

    /// <summary>
    /// Get the height of an image according to the rendered sprite and the desired width(if is not specified, it will take the width of the own image's recTransform)
    /// </summary>
    public static float GetDesiredHeigth(this Image img, float desiredWidth = default)
    {
        RectTransform ImageRect = img.GetComponent<RectTransform>();
        float _bodyWidth = desiredWidth == default ? ImageRect.rect.width : desiredWidth;
        float _imageWidth = (float)img.sprite.texture.width;
        float _imageHeight = (float)img.sprite.texture.height;
        float _ratio = _imageWidth / _imageHeight;
        float _expectedHeight = _bodyWidth / _ratio;
        return _expectedHeight;
    }
    

    所以你可以这样使用它:

    public Image image;
    
    private void AdjustImageSizeToTextureRendered()
    {
        float desiredHeigth = image.GetDesiredHeigth();
        image.rectTransform.sizeDelta = new Vector2(image.rectTransform.sizeDelta.x, desiredHeigth);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      相关资源
      最近更新 更多