您当前的位置: 首页 >  unity

unity工具人

暂无认证

  • 2浏览

    0关注

    205博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

unity工具人 发布时间:2021-09-01 23:00:14 ,浏览量:2

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();
        if (!lockHeight)
        {
            parentHeight = self.parent.GetComponent().rect.size.y - heightBoder;
        }
        self.GetComponent().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();
        parentSize = self.parent.GetComponent().rect.size;        
        ReferHeight = parentSize.y - FrameThickness;
        ReferWidth = parentSize.x - FrameThickness;
        self.GetComponent().SetNativeSize();
        olSize = self.sizeDelta;      
        al = olSize.x / olSize.y;        
        if (olSize.x             
关注
打赏
1656671177
查看更多评论
0.0807s