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上
效果
可以看到无论过长或者过宽图片都会自适应放大和缩小,并且不会改变图片的比例。
原文地址:https://blog.csdn.net/a71468293a/article/details/135999127
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/227695.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/227695.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!