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

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

相关推荐

  1. Flutter 屏幕之相对尺寸

    2024-02-06 22:24:01       23 阅读
  2. Android 如何通过屏幕大小来不同大小的图片

    2024-02-06 22:24:01       14 阅读
  3. 【Android】App 屏幕方案

    2024-02-06 22:24:01       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-06 22:24:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-06 22:24:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-06 22:24:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-06 22:24:01       18 阅读

热门阅读

  1. MySQL深入——18

    2024-02-06 22:24:01       30 阅读
  2. FastAdmin

    2024-02-06 22:24:01       36 阅读
  3. H12-821_315

    2024-02-06 22:24:01       29 阅读
  4. 数组对象过滤

    2024-02-06 22:24:01       32 阅读
  5. k8s的Deployment部署策略线上踩坑

    2024-02-06 22:24:01       26 阅读
  6. 算法.1-三大排序算法-对数器-二分

    2024-02-06 22:24:01       27 阅读
  7. 软件系统架构的演变历史介绍

    2024-02-06 22:24:01       30 阅读
  8. OpenHarmony开源鸿蒙开发之旅

    2024-02-06 22:24:01       33 阅读
  9. 系统架构设计师-21年-上午答案

    2024-02-06 22:24:01       28 阅读