美文网首页
UGUI使用心得1

UGUI使用心得1

作者: LEO_青蛙 | 来源:发表于2020-02-29 22:12 被阅读0次

Camera、Canvas和CanvasScaler的关系

Camera的Projection有2种模式
1、Perspective(透视)
2、Orthographic(正交)
正交Camera的可调参数是Size,Size的定义为视体的投影平面高的1/2。 比如Camera的Size是300,即投影平面高为600。当我们的屏幕高度为1280,即投影平面高为1280,所以Camera的Size设为640。如果Size不设为640,Canvas的Scale就不等于1,如下图:Size为5,Canvas的Scale为0.00781。


image.png
image.png

Canvas的RenderMode有3种方式
1、Screen Space - Overlay(屏幕空间)
2、Screen Space - Camera(世界空间,常用方式)
3、World Space(世界空间)

CanvasScaler的UIScaleMode有3种方式
1、Constant Pixel Size(恒定的像素大小)
2、Scale With Screen Size(与屏幕大小共同缩放,常用方式)
3、Constant Physical Size(恒定的物理尺寸)


image.png

CanvasScaler的UIScaleMode为Scale With Screen Size时,Screen Match Mode有3种方式
1、Match Width Or Height(根据长宽的Match值进行调整)
2、Expand(使用长宽中最小的比例进行缩放)
3、Shrink(使用长宽中最大的比例进行缩放)
具体的代码实现如下:

protected virtual void HandleScaleWithScreenSize()
{
    Vector2 screenSize = new Vector2(Screen.width, Screen.height);

    float scaleFactor = 0;
    switch (m_ScreenMatchMode)
    {
        case ScreenMatchMode.MatchWidthOrHeight:
        {
            // We take the log of the relative width and height before taking the average.
            // Then we transform it back in the original space.
            // the reason to transform in and out of logarithmic space is to have better behavior.
            // If one axis has twice resolution and the other has half, it should even out if widthOrHeight value is at 0.5.
            // In normal space the average would be (0.5 + 2) / 2 = 1.25
            // In logarithmic space the average is (-1 + 1) / 2 = 0
            float logWidth = Mathf.Log(screenSize.x / m_ReferenceResolution.x, kLogBase);
            float logHeight = Mathf.Log(screenSize.y / m_ReferenceResolution.y, kLogBase);
            float logWeightedAverage = Mathf.Lerp(logWidth, logHeight, m_MatchWidthOrHeight);
            scaleFactor = Mathf.Pow(kLogBase, logWeightedAverage);
            break;
        }
        case ScreenMatchMode.Expand:
        {
            scaleFactor = Mathf.Min(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
            break;
        }
        case ScreenMatchMode.Shrink:
        {
            scaleFactor = Mathf.Max(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
            break;
        }
    }

    SetScaleFactor(scaleFactor);
    SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit);
}

Match Width Or Height模式下,Match Height效果图:高度保持不变,宽度拉伸


image.png

Expand模式下的效果图:


image.png
Shrink模式下的效果图:
image.png

相关文章

网友评论

      本文标题:UGUI使用心得1

      本文链接:https://www.haomeiwen.com/subject/oocmhhtx.html