Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

At present, there are various shapes of mobile phone screens, such as fringe screen, hole screen, water drop screen and so on. This brings a question to game development: how can game UI adapt to the irregular screen of mobile phone?

1. Solutions

Cosos Creator provides a component of SafeArea, which obtains the security zone in Android, iOS and other special-screen devices, and then ADAPTS the node layout of the component to the security zone.

The SafeArea component depends on the Widget component, which is automatically added when a SafeArea component is added (if it is not already on the node), and the SafeArea node needs to be removed before the Widget node can be removed.

The SafeArea component is generally used as the top node of the UI interaction area. When enabled, the component obtains the security area of the current device through cc.sys.getSafeArearect () and ADAPTS the layout through the Widget component.

If the current device has an irregular screen, the node layout is adapted to the security area of the irregular screen. If the current device has an ordinary screen, the node layout is designed.

1.1 Adding a Vm Manually

To add a SafeArea component, select a node and click Add Component > UI Component > SafeArea.

1.2 Add through code

If you want code dynamics, you can add SafeArea components to the node during initialization as follows:

this.node.addComponent(cc.Widget);
this.node.addComponent(cc.SafeArea);
Copy the code

Used in 1.3 FairyGUI

When the project uses FairyGUI for UI creation, the root UI node is fgui.groot.inst. node, which is added as follows:

fgui.GRoot.inst.node.addComponent(cc.Widget);
fgui.GRoot.inst.node.addComponent(cc.SafeArea);
Copy the code

In addition, because FairyGUI does not implement its adaptive layout through Widget components, the width height of the GRoot node needs to be set to the width height of the security zone.

fgui.GRoot.inst.width = cc.sys.getSafeAreaRect().width;
fgui.GRoot.inst.height = cc.sys.getSafeAreaRect().height;
Copy the code

2. Pay attention to

If the SafeArea module is invalid, check whether the SafeArea module is selected in Project > Project Settings > Module Settings.

3. Reference materials

  1. SafeArea component Reference