Android Display Metrics in Unity 3D

When designing your Unity 3D GUI for iOS, you get to work with set resolutions and can target each one exactly. But with Android, you have a multitude of devices you can target. How can you make sure a button is the same physical size on all devices? You don’t want a nicely sized button to be suddenly an inch across when running on a tablet.

Luckily you don’t really have to do much work to create UI that is physically the same size across all Android devices. Google has already done the hard work for you and given you the data you need to scale your UI correctly.

Everything in the standard Android SDK layout is based on DiP, or DP (Device independent pixels). When you design a layout for Android, you build it in DPs instead of pixels. A DP is 1 pixel on a device that has a physical 160 DPI.

The simplest way, and the way I do it, is to build my GUI (with NGUI at the moment) as if I am building it for a 160DPI screen. And attach a script to each object to scale it at run-time. All the script does is multiply the current size of the GUI element by DisplayMetricsAndroid.Density.

The code below allows you to grab a lot of info about the Android device you are running on, Density will give you exactly what you need to multiply your 160DPI GUI to re-size it to be the exact same physical size on each device.

For instance, on a phone with 320DPI, DisplayMetricsAndroid.Density will be 2.0; Your GUI will need to be scaled twice as large as if it was on a 160DPI phone screen. On a tablet with 320DPI, DisplayMetricsAndroid.Density might actually still be 1.0. Because the tablet has a larger screen, you don’t need to change your GUI scale, it’s already the correct physical size.

You might have to play around a little bit to understand what’s going on, but until then. Just build for 160DPI, and scale each element at run-time by multiplying it by DisplayMetricsAndroid.Density. You can read a LOT more in Google’s areticle about how they support multiple screen sizes and density support.


Leave a Reply