Unity3d 如何缩放图像中各种大小的精灵大小?

Unity3d 如何缩放图像中各种大小的精灵大小?,unity3d,Unity3d,我有一堆不同高度和宽度的精灵。我想让它们按比例缩放,这样它们就不会被拉伸 现在每一张图片都填满了可用的空间 public GameObject AnimationArea; private float animationHeightBase; private float animationWidthBase; Image positionImage; 我首先得到我希望图像显示的区域的基本大小 void Start() { RectTransform rt = (RectTransfo

我有一堆不同高度和宽度的精灵。我想让它们按比例缩放,这样它们就不会被拉伸

现在每一张图片都填满了可用的空间

public GameObject AnimationArea;
private float animationHeightBase;
private float animationWidthBase;

Image positionImage;
我首先得到我希望图像显示的区域的基本大小

void Start()
{
    RectTransform rt = (RectTransform)AnimationArea.transform;
    animationHeightBase = rt.rect.height;
    animationWidthBase = rt.rect.width;
}
此部分选择将显示的图像

void WhichSideUp()
{
    switch (sideUp)
    {
        case 6:
            height = imageSide5.bounds.size.y;
            width = imageSide5.bounds.size.x;
            positionImage.sprite = imageSide5; // Sprite to Image
            Resize(); //Set the size of the image
            break;
        case 5:
            height = imageSide4.bounds.size.y;
            width = imageSide4.bounds.size.x;
            positionImage.sprite = imageSide4; // Sprite to Image
            Resize(); //Set the size of the image
            break;
        case 4:
            SAME
        case 3:
            SAME
        case 2:
            SAME
        case 1:
            SAME
        default:
            break;
    }
我试图根据高度是否大于宽度或宽度>高度来调整图像大小

void Resize()
{
    float imgScalex;
    float imgScaley;

    if(height > width)
    {
        float ratio = width / height;
         imgScalex = (animationHeightBase * ratio);
         imgScaley = animationHeightBase;
    } else
    {
        float ratio = height / width;
        imgScalex = animationWidthBase;
        imgScaley = (animationWidthBase * ratio);
    }

    positionImage = new Vector2(imgScalex, imgScaley);  //this is where I am failing
}

我必须做一个变通,把代码修改一下。我最终改变了图像的比例,改变了大小。看起来效果不错。我还必须玩天平,这样它看起来会很好看

void Resize()
{
    float imgScalex;
    float imgScaley;
    if(height > width)
    {
        float ratio = width / height;         
        imgScaley = 1;
        imgScalex = ratio * .75f;  /added the .75 because it wasn't scaling properly
    } else
    {
        float ratio = height / width;   
        imgScaley = ratio * 1.5f; /added the 1.5 because it wasn't scaling properly
        imgScalex = 1;
    }
    positionImage.transform.localScale = new Vector2(imgScalex, imgScaley);

如果你改变了比例,你不应该考虑纵横比,所以只要把(0.5,0.5)放进去,它的宽度和高度都是一半,纵横比是一样的。*75f和*1.5f没有意义。