本文是通过设置图片的RectTransform属性达到黑边遮挡效果。
在canvas下建立两个黑边物体并赋予想要的黑边图片。
canvas做如下设置
将我们的脚本挂载在canvas运行
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class 黑边 : MonoBehaviour
{
public float 宽;
public float 高;
public float 宽高比;
public float 规定宽高比;
public RectTransform []rect;//黑边
// Start is called before the first frame update
void Start()
{
规定宽高比 = 1920f / 1080f;
rect = GetComponentsInChildren<RectTransform>();
}
// Update is called once per frame
void Update()
{
宽 = Screen.width;
高 = Screen.height;//获取屏幕宽高信息
宽高比 = 宽 / 高;
if (宽高比 >= 规定宽高比)
{
左右黑边();
}
if (宽高比 < 规定宽高比)
{
上下黑边();
}
}
public void 左右黑边()
{
rect[2].anchorMax = new Vector2(0, 0.5f);//锚点
rect[2].anchorMin = new Vector2(0, 0.5f);//锚点
rect[2].anchoredPosition = new Vector2(0, 0);//位置
rect[2].pivot = new Vector2(0f, 0.5f);//轴心
rect[2].sizeDelta = new Vector2(((宽高比* rect[0].sizeDelta.y) - rect[0].sizeDelta.y * 规定宽高比) / 2, rect[0].sizeDelta.y);
rect[1].anchorMax = new Vector2(1, 0.5f);
rect[1].anchorMin = new Vector2(1, 0.5f);
rect[1].anchoredPosition = new Vector2(0, 0);
rect[1].pivot = new Vector2(1f, 0.5f);
rect[1].sizeDelta = new Vector2(((宽高比 * rect[0].sizeDelta.y) - rect[0].sizeDelta.y * 规定宽高比) / 2, rect[0].sizeDelta.y);
}
public void 上下黑边()
{
rect[2].anchorMax = new Vector2(0.5f, 1f);//锚点
rect[2].anchorMin = new Vector2(0.5f, 1f);//锚点
rect[2].anchoredPosition = new Vector2(0, 0);//位置
rect[2].pivot = new Vector2(0.5f, 1f);//轴心
rect[2].sizeDelta = new Vector2(rect[0].sizeDelta.x, ((rect[0].sizeDelta.x/ 宽高比) - rect[0].sizeDelta.x / 规定宽高比) / 2);
rect[1].anchorMax = new Vector2(0.5f, 0);
rect[1].anchorMin = new Vector2(0.5f, 0);
rect[1].anchoredPosition = new Vector2(0, 0);
rect[1].pivot = new Vector2(0.5f, 0);
rect[1].sizeDelta = new Vector2(rect[0].sizeDelta.x, ((rect[0].sizeDelta.x / 宽高比) - rect[0].sizeDelta.x / 规定宽高比) / 2);
}
}
运行后不同分辨率下效果