UGUI在处理自适应Canvas Scaler。
我们要做的就是3DCamera的自适应。把下面这个脚本挂在Main Camera上即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
using
UnityEngine
;
using
System
.
Collections
;
using
UnityEngine
.
UI
;
public
class
CameraScale
:
MonoBehaviour
{
void
Start
(
)
{
int
ManualWidth
=
960
;
int
ManualHeight
=
640
;
int
manualHeight
;
if
(
System
.
Convert
.
ToSingle
(
Screen
.
height
)
/
Screen
.
width
>
System
.
Convert
.
ToSingle
(
ManualHeight
)
/
ManualWidth
)
manualHeight
=
Mathf
.
RoundToInt
(
System
.
Convert
.
ToSingle
(
ManualWidth
)
/
Screen
.
width *
Screen
.
height
)
;
else
manualHeight
=
ManualHeight
;
Camera
camera
=
GetComponent
<
Camera
>
(
)
;
float
scale
=
System
.
Convert
.
ToSingle
(
manualHeight
/
640f
)
;
camera
.
fieldOfView*
=
scale
;
}
}
|
rectTransform.sizeDelta = new Vector2(Screen.width,Screen.height);
把如下脚本挂在需要全屏的Image对象上即可。
using
UnityEngine
;
using
System
.
Collections
;
public
class
UIMaskLayer
:
MonoBehaviour
{
void
Start
(
)
{
int
width
=
Screen
.
width
;
int
height
=
Screen
.
height
;
int
designWidth
=
960
;
//开发时分辨率宽
int
designHeight
=
640
;
//开发时分辨率高
float
s1
=
(
float
)
designWidth
/
(
float
)
designHeight
;
float
s2
=
(
float
)
width
/
(
float
)
height
;
if
(
s1
<
s2
)
{
designWidth
=
(
int
)
Mathf
.
FloorToInt
(
designHeight *
s2
)
;
}
else
if
(
s1
>
s2
)
{
designHeight
=
(
int
)
Mathf
.
FloorToInt
(
designWidth
/
s2
)
;
}
float
contentScale
=
(
float
)
designWidth
/
(
float
)
width
;
RectTransform
rectTransform
=
this
.
transform
as
RectTransform
;
if
(
rectTransform
!=
null
)
{
rectTransform
.
sizeDelta
=
new
Vector2
(
designWidth
,
designHeight
)
;
}
}
}