【unity3d】GUI 图像自动适配屏幕大小

本文介绍了一个Unity3D中的组件AutoUiSize,用于确保图像在不同屏幕尺寸下保持清晰显示,通过检测屏幕大小并调整其比例以适应。组件在运行模式中工作,面板填充背景,Image组件使用AutoUiSize组件实现自适应缩放。
摘要由CSDN通过智能技术生成

目的

图像大小是固定,直到屏幕的大小小于这个图像大小时,图像在保持自身长宽不变的情况下,缩小到可以在这个屏幕中完整观看的尺寸。

结果

目前需要跑运行模式,而且要作为该图的组件

在这里插入图片描述

对象设置

  1. 组织:
    在这里插入图片描述
  2. background的Canvas设置
    在这里插入图片描述
  3. Panel设置为填满
    在这里插入图片描述
  4. Image 加入"AutoUiSize"的组件(下面有代码),设置为居中
    在这里插入图片描述

代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoUiSize : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    void UpdateSize(){
        RectTransform rt = GetComponent<RectTransform>();
        
        if(rt.rect.width > Screen.width || rt.rect.height > Screen.height){
            if(Screen.width / Screen.height < rt.rect.width / rt.rect.height ){
                float scale =  Screen.width / rt.rect.width;
                rt.localScale = new Vector3(scale, scale, scale);
                Debug.Log("Scale is " + scale);
            }else{
                float scale = Screen.height / rt.rect.height;
                rt.localScale = new Vector3(scale, scale, scale);
                Debug.Log("Scale is " + scale);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {   
        UpdateSize();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值