unity中全屏背景图缩放

本文介绍了一种在Unity中实现UI界面自适应不同分辨率设备的方法。通过调整UIRoot的属性和利用BgPicScript脚本,使得UI元素能够根据不同设备屏幕尺寸进行自动缩放,保持设计的一致性和美观性。

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

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class BgPicScript : MonoBehaviour {
 5 
 6     // Use this for initialization
 7     public UITexture bg;
 8     void Start () {
 9 
10         Debug.Log("device宽高: " + Screen.width + "_" + Screen.height);
11 
12         UIRoot root = GameObject.FindObjectOfType<UIRoot>();
13 
14         if (root != null) 
15         {
16             //终极大杀器 整体资源缩放比例
17             float s = (float)root.activeHeight / Screen.height;
18             int height =  Mathf.CeilToInt(Screen.height * s);
19             int width = Mathf.CeilToInt(Screen.width * s);
20           
21             Debug.Log("按设计分辨率屏幕width = " + width + "_height = " + height);
22 
23             Debug.Log("背景图片的设计分辨率bgWIdth:" + bg.width + "_bgHeight:" + bg.height);
24 
25             float bgRatio = (float) bg.width / bg.height;
26             float manualRatio = (float)width / height;
27 
28 
29             if (bgRatio < manualRatio) //遇到按照屏幕高度缩放水平两边出现黑边的情况,要按照宽度来缩放背景图片
30             {
31                 //bg.width = width;
32                 //bg.height = Mathf.CeilToInt(width / );
33 
34                 float targetScale = (float)width / bg.width;
35                 bg.transform.localScale = new Vector3(targetScale,targetScale, 1);
36             }
37         }
38 
39       
40     }
41     
42     // Update is called once per frame
43     void Update () {
44     
45     }
46 }
47 
48 
49 
50 using UnityEngine;
51 using System.Collections;
52 
53 public class UIRootScript : MonoBehaviour {
54 
55     // Use this for initialization
56     void Start () {
57         AdaptiveUI();
58     }
59     
60     // Update is called once per frame
61     void Update () {
62     
63     }
64 
65     static private void AdaptiveUI()
66     {
67         int ManualWidth = 1024;
68         int ManualHeight = 768;
69         UIRoot uiRoot = GameObject.FindObjectOfType<UIRoot>();
70         if (uiRoot != null)
71         {
72             if (System.Convert.ToSingle(Screen.height) / Screen.width > System.Convert.ToSingle(ManualHeight) / ManualWidth)
73                 uiRoot.manualHeight = Mathf.RoundToInt(System.Convert.ToSingle(ManualWidth) / Screen.width * Screen.height);
74             else
75                 uiRoot.manualHeight = ManualHeight;
76         }
77         Debug.Log("uiRoot Height:" + uiRoot.manualHeight);
78     }
79 }

 

转载于:https://www.cnblogs.com/JD85/p/4648768.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值