当前位置: 首页 > article >正文

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


http://www.kler.cn/a/227695.html

相关文章:

  • CSS transition(过渡效果)详解并附带示例
  • Python新春烟花盛宴
  • Linux 网络编程 + 笔记
  • 实现屏蔽 Ctrl + Alt + Del 、Ctrl + Shift + Esc 等热键(二)
  • 系统架构-性能评估
  • TCP TIME_WAIT 过多怎么处理
  • ios搭建OpenGL环境
  • 数据结构与算法面试系列-02
  • c++类继承
  • 从编程中理解:大脑的自我实现预言
  • 【国产MCU】-CH32V307-GPIO控制-外部中断
  • C++设计模式-简单工厂模式,工厂方法模式,抽象工厂模式
  • 头歌C++语言之数学运算练习题(二)
  • 设计模式——七大原则
  • Android学习之路(27) ProGuard,混淆,R8优化
  • uniapp中使用EelementPlus
  • css1文本属性
  • Nginx双域名管理内网服务
  • Intellij IDEA各种调试+开发中常见bug
  • mysql 锁知识汇总