原理:获取iOS底层安全区范围 返回到游戏层 对画布进行重新设置
游戏层代码:SetCanvasBounds.cs 拖入画布 和画布子物体RectTransform
文章末尾有链接
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class SetCanvasBounds : MonoBehaviour {
#if UNITY_IOS
[DllImport("__Internal")]
private extern static void GetSafeAreaImpl(out float x, out float y, out float w, out float h);
#endif
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);
}
public RectTransform canvas;
public RectTransform panel;
Rect lastSafeArea = new Rect(0, 0, 0, 0);
// Use this for initialization
void Start () {
}
void ApplySafeArea(Rect area)
{
var anchorMin = area.position;
var anchorMax = area.position + area.size;
anchorMin.x /= Screen.width;
anchorMin.y /= Screen.height;
anchorMax.x /= Screen.width;
anchorMax.y /= Screen.height;
panel.anchorMin = anchorMin;
panel.anchorMax = anchorMax;
lastSafeArea = area;
}
// Update is called once per frame
void Update ()
{
Rect safeArea = GetSafeArea(); // or Screen.safeArea if you use a version of Unity that supports it
if (safeArea != lastSafeArea)
ApplySafeArea(safeArea);
}
}
底层代码(也就是放在unityplugin文件夹下代码)
SafeAreaImpl.mm
#include <CoreGraphics/CoreGraphics.h>
#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;
}
编辑器:
效果: