Unity 图片不改变比例适配屏幕

本文介绍了如何在Unity项目中编写AdaptiveImageBackground脚本来使图片根据相机大小填充屏幕,同时保持图片的原始比例,通过RectTransform组件进行尺寸调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity 图片不改变比例适配屏幕

前言

遇到一个要让图片适应相机大小,填满屏幕,但不改变图片比例的需求,记录一下。

项目

场景布置

场景布置

代码编写

创建AdaptiveImageBackground脚本

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

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            AdaptiveFunction();
        }
    }

    /// <summary>
    /// 自适应背景
    /// </summary>
    private void AdaptiveFunction()
    {
        RectTransform parentRect = transform.parent.GetComponent<RectTransform>();
        RectTransform rectTransform = GetComponent<RectTransform>();

        float parentAspect = parentRect.rect.width / parentRect.rect.height;
        float imageAspect = rectTransform.rect.width / rectTransform.rect.height;

        // 比较父容器的宽高比和图片的宽高比
        if (parentAspect > imageAspect)
        {
            // 父容器更宽,调整图片的大小以填满宽度
            rectTransform.sizeDelta = new Vector2(parentRect.rect.width, parentRect.rect.width / imageAspect);
        }
        else
        {
            // 父容器更高,调整图片的大小以填满高度
            rectTransform.sizeDelta = new Vector2(parentRect.rect.height * imageAspect, parentRect.rect.height);
        }
    }
}

添加并设置脚本

挂在需要适配的Image上
挂载脚本

效果

可以看到无论过长或者过宽图片都会自适应放大和缩小,并且不会改变图片的比例。
2340
3200

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值