Pixel perfect layout in Tabris.js

September 4, 2015 | 2 min Read

Positioning widgets in a layout is a very common task in Tabris.js apps. When dealing with varying device densities, Tabris.js lets you declare all dimensions in device independent pixels. This ensures that a layout will look the same on high and low resolution displays.

Providing device independent pixels means that you can only provide positions with a multiple of the base density of the display. So a device with a 4x density would only allow layout data that would hit the pixels at 0, 4, 8,… etc.

While that is a fine approach, there might be situations where you actually have to be pixel perfect. For example when you get the bounds from a widget after a layout pass and the layout algorithm puts the widget at pixel 3 on a 4x display. This means you would not be able to retrieve the value as an integer number. Or you might get the scroll position of a ScrollView which could return any number.

To remedy that problem Tabris.js (1.2+) allows you to set and get layout related information as fractions.

tabris.create("Composite", {
  background: "green",
  layoutData: {left: 0.25, top: 0.25, width: 100, height: 100}
}).appendTo(page);

The following screenshot demonstrates the different layout results in physical pixel on a 4x device:

A small reminder in the end. If you want to get the density of the current device use:

var scaleFactor = tabris.device.get("scaleFactor");
var onePhysicalPixel = scaleFactor / 1;

You can check out all the above code immediately on your device, as well as test your own code. To do that, download the Tabris.js Developer App:

[

tabrisjs.com