Unity 图片原比例适应父物体大小

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class X_RectAutoSize : MonoBehaviour
{
    //原始尺寸
    private Vector2 olSize;
    //缩放后的尺寸
    private Vector2 size;
    //原始尺寸宽高比
    private float al;
    private RectTransform self;
    public bool lockHeight;
    public bool lockPos= true;
    internal float parentHeight;
    public float heightBoder;

    void Update()
    {
        self = GetComponent<RectTransform>();
        if (!lockHeight)
        {
            parentHeight = self.parent.GetComponent<RectTransform>().rect.size.y - heightBoder;
        }
        self.GetComponent<Image>().SetNativeSize();
        olSize = self.sizeDelta;
        al = olSize.x / olSize.y;
        size = new Vector2(parentHeight * al, parentHeight);
        self.sizeDelta = size;
        if (lockPos)
        {
            self.anchoredPosition = Vector2.zero;
        }
    }
}

原文地址:https://www.cnblogs.com/lovewaits/p/8276242.html
不过这个写法中的图片尺寸是以父物体高度为基准来进行缩放的,所以下边的版本中做了一点点小小的修改,以图片较长的一条边为基准来进行缩放

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class X_RectAutoSize : MonoBehaviour
{
    //原始尺寸
    private Vector2 olSize;
    //缩放后的尺寸
    private Vector2 size;
    //原始尺寸宽高比
    private float al;
    private RectTransform self;
    public bool lockPos = true;        
    internal float ReferHeight;
    internal float ReferWidth;
    private Vector2 parentSize;      
    public float FrameThickness;

    void Update()
    {
        SetWidthHight();        
    }

    //设置宽高
    public void SetWidthHight()
    {
        self = GetComponent<RectTransform>();
        parentSize = self.parent.GetComponent<RectTransform>().rect.size;        
        ReferHeight = parentSize.y - FrameThickness;
        ReferWidth = parentSize.x - FrameThickness;
        self.GetComponent<Image>().SetNativeSize();
        olSize = self.sizeDelta;      
        al = olSize.x / olSize.y;        
        if (olSize.x < olSize.y)
        	size = new Vector2(ReferHeight * al, ReferHeight); 
        else
        	size = new Vector2(ReferWidth, ReferWidth / al);
       
        self.sizeDelta = size;      
        if (lockPos)
            self.anchoredPosition = Vector2.zero;
    }
}
posted @ 2022-06-22 18:04  哒哒哒~~~  阅读(337)  评论(0)    收藏  举报