BLOG

Notes from the KAYAC hyper-casual team

Making Multi-Resolution SafeArea Support in Unity Less Painful

Takashi Hirayama

Mobile development means dealing with all sorts of devices. All sorts of resolutions, all sorts of aspect ratios. These days there are even devices with chunks of the screen missing, which only guarantee that things will be visible if they fit inside a certain area (the safeArea).

So what's the least painful way to deal with all this?

I'm Hirayama from the Technology Department, and I'll show one example, based on the approach we used in our Tokyo Prison.

Here's what we're after

Let's look at an example like this one.

Example layout at 1280x720

This screen has five elements.

  • The green elliptical window. I want its buttons top-aligned inside the safeArea, and its size to stay at a fixed ratio to the screen width.
  • The blue elliptical window. I want its buttons left-aligned inside the safeArea, and its size to stay at a fixed ratio to the screen height.
  • The red elliptical window. I want it in the center of the safeArea. I want it to fit on screen at any resolution.
  • The character art on the right. I want it aligned to the bottom right, ignoring the safeArea. I want it to fit on screen at any resolution.
  • The background. I want it to fill the whole screen.

The actual resolution here (Screen.width and Screen.height) is 1280x720, or 16:9. A very common resolution.

Now let's take this to a 4:3 device (an iPad or similar). Let's say the whole screen is inside the safeArea, and the resolution is 1024x768.

The same layout at 1024x768

The height has increased, so the blue ellipse has gotten bigger. That's because it's defined as "half the height." Meanwhile, the character art takes up a smaller share of the screen.

Next, let's try a 2436x1125 device with parts of the screen edges cut away: the iPhone X. The 132 pixels on the left and right and the 63 pixels at the bottom are risky places to put things.

The same layout at 2436x1125, with the area outside the safeArea framed in red

Think of the red frame around the edge as the part you can't use because of the notch and so on. In other words, the area outside the so-called safeArea. For the blue ellipse, the buttons are placed against the left edge of the safeArea, but the ellipse is drawn beyond it too. That's because, safeArea or not, it would look bad if the ellipse were cut off right there. The character art is currently placed bottom-right, ignoring the safeArea, so some of it sticks out of the safeArea. In a real product, it might be better to keep the character art inside.

While we're at it, let's try an even more extreme resolution: 432x768, which is portrait.

The same layout at 432x768 in portrait

For good measure, I also put 10 pixels on the left, 20 on the right, 30 at the top and 40 at the bottom outside the safeArea. The blue ellipse has gotten even bigger. The green one got smaller because it's defined as "half the screen width." The character art has gotten smaller too. At this point, it doesn't look like you can get away with zero effort. Even so, nothing "sticks out of the screen," "shows something that shouldn't be shown" or "leaves areas unpainted."

And of course, I didn't fiddle with the layout for each of these four screenshots. I only changed the GameView resolution and entered a few numbers defining the safeArea in the inspector. In Tokyo Prison, we use a component that automatically scales and positions layout elements like these, which reduces the cost of supporting multiple resolutions.

In this article, I'll write about how it's implemented and how it's used. The sample code is published on GitHub, including the component's source code.

How to use it

Anyone making games has probably built something like this already, so there's little point in explaining in detail how to use this code. Still, I think there's a lot to be learned from how it feels to use, so I'll go over it briefly.

Note that what I'm presenting here is based on the implementation in Tokyo Prison, but it isn't identical. Some things I changed when extracting it into a sample, and some things I improved further.

First, attach the component

The first thing to do is attach a component called RectTransformScaler to the gameObject at the root of a layout element. As an example, let's look at the left-aligned blue ellipse.

The RectTransformScaler component on the LeftAligned gameObject in the inspector

The component is attached to a gameObject called LeftAligned. The blue ellipse, buttons and so on are placed as its children.

Now let's go through the settings one at a time.

RectTransform width and height

LeftAligned's width/height are 1280 and 720, which means "everything under LeftAligned is rendered at a virtual resolution of 1280x720." Whether the actual resolution is 1920x1080 or 1024x768, it's scaled and positioned appropriately. You can lay out everything under LeftAligned as if the screen were 1280x720.

Scale Mode

What the scaling is based on. Here it's Vertical, which means "based on the screen height." The virtual resolution is 1280x720, so the height is 720, and whatever the actual resolution, everything is scaled so the screen height corresponds to 720. For example, at 1920x1080, 720 is enlarged to 150% and drawn at a size of 1080; at 854x480, 720 is shrunk to 66% and drawn at a size of 480.

There are four options:

  • Horizontal: based on the parent's width.
  • Vertical: based on the parent's height.
  • Min: based on the smaller of the parent's width and height.
  • Max: based on the larger of the parent's width and height.

The green ellipse is Horizontal, so its scale is determined by the width. The red ellipse is Min, so it fits the width in portrait and the height in landscape. As a result, whatever the aspect ratio, the whole thing fits on screen and never sticks out. The background is Max, so it fits the height in portrait and the width in landscape. As a result, whatever the aspect ratio, it fills the whole screen, and some part of it almost always sticks out.

Horizontal Anchor

Which side to align to when there's extra width. For example, when width/height is 1280x720 and the actual resolution is 2436x1125, if ScaleMode is Vertical, the scale is 156%, enlarging 720 to 1125. As a result, the width of 1280 becomes 2000, leaving about 436 pixels to spare. This setting lets you choose whether to align it left, right or center.

For the blue ellipse (LeftAligned), this is set to Left, so it's left-aligned. You use this to left-align things on wide devices like the iPhone X. The character art, on the other hand, is Right, so it's right-aligned.

Vertical Anchor

Whether to align to the top or bottom when there's extra height. For example, when width/height is 1280x720 and the actual resolution is 1024x768, if ScaleMode is Horizontal, the scale is 80%, shrinking 1280 to 1024. As a result, the height becomes 576, leaving about 192 pixels to spare.

The green ellipse is Top, so it's top-aligned. The character art is Bottom, so it's bottom-aligned.

Use Margin

Basically, whether to take the safeArea into account. In the example, the blue, green and red ellipses have this set to true, so they're laid out to fit inside the red frame. The left edge of the blue ellipse doesn't fit because the ellipse was placed sticking out of the 1280x720 virtual area to begin with. This allows a layout where the edge is cut off on 16:9 and 4:3 devices, while on wider devices like the iPhone X the hidden edge comes into view.

You'll usually design the game screen around 16:9, but sometimes you'll want a layout where a frame or window sticks out of the screen, as in the example. But to keep it from breaking on the iPhone X, you'd have to extend the frame quite far beyond the screen, which makes the assets bigger and looks worse, too. So in Tokyo Prison, we went with a design where "on a wide enough screen, the edges come into view."

A Tokyo Prison screen where the window edge is cut offThe same screen on a wider device, with the window edge in view

Preview

An editor extension adds two buttons here, and pressing them applies the settings above to the layout. "ここだけApply" (apply here only) affects "this RectTransform only," and "再帰的Apply" (apply recursively) processes every RectTransformScaler below it in the hierarchy.

In fact, in the version in Tokyo Prison, the apply step was called from OnValidate, so changing a setting took effect immediately. But that causes scenes and prefabs to change at unexpected times. When you change the gameView resolution, the RectTransformScalers in the open scene run and rewrite the RectTransform's anchorMin, anchorMax, pivot, scale, posX and posY, and strange diffs show up when you commit to git. Since everyone on the team sets the gameView to a different resolution, this happens a lot.

So when turning it into a sample, I made it manual. Of course, the apply step runs in MonoBehaviour.Start, so at runtime the layout happens automatically.

Initialization

At runtime, you need to do some initialization. You have to tell the component the dimensions of the safeArea.

In the product, a separate class held the resolution and margins, and RectTransformScaler read them from there, but I changed this for the sample. Here, the margins are held in a static variable of RectTransformScaler.

Below is the MonoBehaviour for initialization placed in the sample scene. It's attached to Main Camera.

public class Sample : MonoBehaviour
{
    // (snip)
    public RectTransform canvasRectTransform;
    public float marginLeft;
    public float marginRight;
    public float marginTop;
    public float marginBottom;

    void Start()
    {
        Apply();
    }

    void Apply()
    {
        var canvasSize = canvasRectTransform.sizeDelta;

        Kayac.RectTransformScaler.SetNormalizedMargin(
            marginLeft / canvasSize.x,
            marginRight / canvasSize.x,
            marginTop / canvasSize.y,
            marginBottom / canvasSize.y);
        // (snip)
#if UNITY_EDITOR
        Kayac.RectTransformScaler.ApplyRecursive(canvasRectTransform);
#endif
    }
}

Start() calls Apply(), which passes the margins set in the inspector to RectTransformScaler.SetNormalizedMargin(). In the editor, it also calls ApplyRecursive() to apply the settings for every RectTransformScaler under the canvas.

In an actual product, the idea is to have some scene that loads before anything is displayed, and call SetNormalizedMargin() there. Any scenes that display things and load after that get laid out correctly in RectTransformScaler's Start(), so you don't need to do anything special.

About the design

This mechanism came out of the following situation.

  • The iPhone X suddenly appeared, and we had to support screens wider than 16:9.
  • We had already built a huge amount of content, so we wanted to minimize the work for artists and Unity-side programmers.
  • A single Canvas contained several parts with different settings (right-aligned or left-aligned, fit to the screen or fill the whole area).

Actually, a similar component that attaches to a Canvas had already been made by Fujii. It's still used in many places, and most of this one's implementation was taken from it (thank you!). But back then, only the equivalent of this article's ScaleMode setting was needed, so it had no settings for left or right alignment and so on. Also, since it worked per Canvas, it couldn't handle multiple parts with different settings under one Canvas. That's why I made a separate, experimental one that can be attached to each RectTransform.

About the settings

In the original Canvas component, the options were named by purpose, like "background," rather than by behavior, like "scale to fit the width." There were three: "background," "full screen" and "fit in the safeArea." For example, "background" ignores the safeArea so that nothing is left unpainted, which corresponds to "ScaleMode=Max, useMargin=true" in this one. Naming them by purpose is usually easier to understand.

Who you design an editor settings UI for is a big question. There's no need to support things nobody will do, so the best UI is the smallest, simplest one that covers everything people will do. But partly because the required features grew, and partly because I figured "I'm the only one who'll use it anyway," this time the settings are simply named after their behavior. If many people were going to use it, I might have added purpose-based options like "background," "left-aligned in safeArea" and "fit width in safeArea."

To tell the truth, it could be made even more general. There are infinitely many steps between left-aligned and centered, and turning Left, Center and Right into a single slider would make it more versatile. In that case, something like this might work well:

  • 0 is the left edge, 0.5 the center, 1 the right edge
  • In between is interpolated. For example, 0.1 aligns to the point 20% in from the left edge of the screen

But there's no point in supporting things we don't need yet, so for now I've deliberately limited it to three options.

In actual use

The aspect ratios Tokyo Prison assumes range from 4:3 to 2.1:1. In other words, the iPad is the limit on the squarer end, and the iPhone X is the limit on the wider end. Beyond this range, the display breaks. Automatic adjustment can only do so much, and even in the screen examples near the top of this article, portrait isn't really handled.

Also, I've only dealt with 2D placement here, but mixing in 3D brings further headaches.

A Tokyo Prison screen with 2D elements over a 3D viewThe same screen at another aspect ratio, with the safeArea shown in red

The 2D elements are drawn on top of what the 3D camera renders. With this mechanism, the 2D elements are split into three parts, aligned bottom-left, bottom-right and center-right, and the safeArea, shown in red, is handled too. But the 3D rendering can't be split, so there's no way to adjust it. In this product, the 3D part is fit to the screen height, so the view feels narrow on the iPad. But if we fit it to the width, the iPad would show too much in the foreground and background, and we'd have to build out the background scenery further. Rather than forcing the placement, covering the extra area with black bars may be better for processing load, usability and looks alike. The same goes even when there's only 2D.

In the end, even with automatic adjustment, there's no getting around testing on real devices. For example, even if a layout is "guaranteed to fit on screen," you can't tell whether things are big enough to tap easily without looking. And you can't tell whether the layout is easy to use without actually touching it. With the arrival of the iPhone X, a device "likely to have lots of owners, yet with an unusual resolution," all that testing and adjusting took quite a lot of effort.

For example, the two face icons in the bottom left of the screenshot above sit a little above the bottom edge because of a string of mis-taps caused by the iOS 11+ behavior where "dragging (swiping) from the screen edge brings up an OS screen." Originally they were at the bottom edge. As you can see, there are pitfalls beyond aspect ratio and the safeArea.

About the implementation

As for the implementation, it's probably quicker to just read the code, so I won't go into detail. Without the editor extension it's about 170 lines, and the core of the coordinate calculation is about 25 lines.

In a nutshell: "take the parent RectTransform's width and height, subtract the margins set in the static variable, calculate a suitable scale from its own width, height and ScaleMode, and set the top/bottom/left/right alignment with anchoredPosition." If the parent RectTransform is, say, 100x100, weird things happen, so it's basically meant to go under a full-screen Canvas or a RectTransform set to full screen. That said, there may be some use in deliberately placing it under one that isn't.

I've also added an item to the GameObject menu that "applies every RectTransformScaler below the selected gameObject." In this sample, a button on the Sample class does the same thing, but in practice the component is used in all sorts of scenes, so I added it to the right-click menu like this. Though, having built it, I have to admit I probably wouldn't miss it much if it weren't there.

The added item in the GameObject right-click menu

Summary

When you make an app that runs on many devices, varying resolutions and aspect ratios are usually a headache. Thanks to the iPhone X, it has gotten even more complicated, and if you don't budget a certain amount of effort for it, you'll have a terrible time later (we did).

For the best layout, working closely with designers and planners is essential, but programmers can at least absorb "a bit of variety" by building a small mechanism like this. This article presented one example of such a mechanism.

I'd love to hear your thoughts and feedback. Also, many people, myself included, would be very happy if you shared case studies from other products, so other companies, please consider it!