Unity3D_屏幕适配

原生安卓可以根据不同的手机厂商(Huawei,XiaoMi等)提供的接口,获取当前手机是否为凹凸屏、全面屏等。Unity3D再根据返回的接口,来调整页面布局。如果是凹凸刘海屏,需要根据Android O,Android P来判断窗体如何渲染拓展到全屏。参考博文:https://blog.csdn.net/wanzi215/article/details/88179295 ;https://blog.csdn.net/SnoopyNa2Co3/article/details/85699987 ;https://www.codetd.com/article/3885160

在Unity2018中已经做了全面屏、刘海屏的适配支持。

iOS方式:原生在XCode里面可以

获取iOS屏幕安全区域:


#include 
#include "UnityAppController.h"
#include "UI/UnityView.h"

CGRect CustomComputeSafeArea(UIView* view)
{
	CGSize screenSize = view.bounds.size;
	CGRect screenRect = CGRectMake(0, 0, screenSize.width, screenSize.height);
	
	UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, 0, 0);
	if ([view respondsToSelector: @selector(safeAreaInsets)])
		insets = [view safeAreaInsets];
	
	screenRect.origin.x += insets.left;
	screenRect.origin.y += insets.bottom; // Unity uses bottom left as the origin
	screenRect.size.width -= insets.left + insets.right;
	screenRect.size.height -= insets.top + insets.bottom;
	
	float scale = view.contentScaleFactor;
	screenRect.origin.x *= scale;
	screenRect.origin.y *= scale;
	screenRect.size.width *= scale;
	screenRect.size.height *= scale;
	return screenRect;
}

extern "C" void GetSafeAreaImpl(float* x, float* y, float* w, float* h)
{
	UIView* view = GetAppController().unityView;
	CGRect area = CustomComputeSafeArea(view);
	*x = area.origin.x;
	*y = area.origin.y;
	*w = area.size.width;
	*h = area.size.height;
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class UISaftyRect : MonoBehaviour
{
#if UNITY_IOS
	[DllImport("__Internal")]
    private extern static void GetSafeAreaImpl(out float x, out float y, out float w, out float h);
#endif

    Rect lastSafeArea;

    void Start()
    {
#if !UNITY_IOS && !UNITY_EDITOR
        this.enabled = false;
#else
        AdjustSaftyRect();
#endif
    }

    void Update()
    {
        //AdjustSaftyRect();
    }

    void AdjustSaftyRect()
    {
        Rect safeArea = GetSafeArea();
        if (safeArea != this.lastSafeArea)
        {
            Rect UIArea = (UIMgr.instance.transform as RectTransform).rect;
            RectTransform rectTransform;
            rectTransform = this.transform as RectTransform;
            DkLog.Log("safeArea.xMin :" + safeArea.xMin+","+ UIArea.width+","+ Screen.width+","+ safeArea.xMax);
            float offset = safeArea.xMin * (UIArea.width / Screen.width);
            rectTransform.offsetMin = new Vector2(offset, 0f);

            offset = (safeArea.xMax - Screen.width) * (UIArea.width / Screen.width);
            rectTransform.offsetMax = new Vector2(offset, 0f);
            this.lastSafeArea = safeArea;
        }
    }

    private Rect GetSafeArea()
    {
        float x, y, w, h;
#if UNITY_IOS
		GetSafeAreaImpl(out x, out y, out w, out h);
#else
        x = 0;
        y = 0;
        w = Screen.width;
        h = Screen.height;
#endif
        return new Rect(x, y, w, h);
    }

}

 

你可能感兴趣的:(Unity3d)