Optical alignment for frontend developers:

Part II — how can the process be automated?

Ivan Grekov
Nov 22, 2018 · 14 min read

In the previous article we defined a list of problems with existing approaches to optical alignment: why alignment is needed, how optical imbalance appears, and why design-based approaches may not be the best solution for frontend developers. It has been just over a year since I first published the full article on the topic and subsequently attended in several Meetups in London, sharing the benefits of the approach that I will describe in this article. I based my updates to the article on some new examples and my own experience while continuing to work on various projects for Badoo on a daily basis.

The first and important thing when dealing with projects on a daily basis is to find a way to make all less skill-intensive work faster and more automated. In the case of optical alignment, it is not an elementary task, but fortunately, it can still be automated!

In this article I would like to share my research on the topic and explain how I examined different hypotheses and theories to create a basis for automation, before finally identifying a fast and reliable solution for everyday use.

Automation

I will continue with the example of the diamond-shaped icon that was briefly described earlier in the previous article. Two possible alignments inside the icon are shown below: the left-hand shape is placed inside a rectangle, while the shape on the right is placed inside a circle. Both containers have been centred in relation to the violet-coloured circular background.

As you can see, both illustrations are far from being in the centre of the shape’s container. In the left-hand icon, your natural instinct is to position the diamond shape lower down — and likewise you want to move the right-hand icon upwards. It therefore appears that the approach of using a circular container is not optimal in this particular case.
I also tried the approach of rotating the icon, which yielded a third result. In each of the three cases, additional actions were required to optimise the alignment, and in each case, this required manual intervention.

However, not everyone has an innate sense of vertical rhythm and an understanding of the role of the Golden Ratio in design. This means that, instead of performing a manual alignment, we need to work from a universal algorithm (in as abstract a manner as possible) to enable us to find the centre point of any shape. Ideally, this optical alignment process needs to be automated. However, before the process can be automated, it needs to be understood. As such, I decided to go beyond the boundaries of graphic design and study existing solutions and theories with a view to performing optical alignment while minimising the time and effort taken.

A little bit of theory

I would like to propose a solution for the problem of optical imbalance which can be derived from basic geometry. In order to perform alignment, the centre point of a geometric shape needs to be defined. In geometry, this is referred to as the barycentre, i.e., the geometric centre point of a shape.

You can consider the barycentre to be the average of the positions of all points in the shape. For this purpose, centre of mass, centre of gravity and barycentre shall all represent a single point in the shape. This assumption is possible since we are working with user interfaces. If we are to define the centre of a model for a 3D object, or the centre point of a geometric perimeter by determining the barycentre, we will have to separate the terms above and add a large number of exceptions to the general rules.

The definition of the barycentre extends to any object in an n-dimensional space. Roughly speaking, this is the equilibrium point of the shape. For user interfaces, what matters is the fact that you can find the correct coordinates to align a shape, by using a formula to determine the barycentre.

The process of finding the barycentre starts with determining what kind of shape we are dealing with. For a range of icons this task is straightforward:

  • The barycentre for squares, rectangles and parallelograms is found at the point of intersection of the diagonal lines. Graphics editors provide the right coordinates for these shapes by default and no optical alignment is required;
  • The barycentre for circles, rings and hexagons is located at the centre point of these shapes and again, graphics editors can handle alignment of the layers;
  • The barycentre for an ellipse is at the intersection of the axis; once again automatic alignment works correctly.

Conclusion: if the icon has a symmetrical centre point, its barycentre will coincide with this central point. In the illustration below, the circle and the square have the same barycentre. However, the pencil icon doesn’t share the barycentre, meaning that additional calculations must be performed. The same applies to many other shapes.

Let me provide an example of such cases with the use of other basic shapes:

  • The barycentre for a triangle is at the intersection of the medians (there are different kinds of triangles, so, having calculated the barycentre, optical alignment is still required);
  • The barycentre of a semi-circle is determined using a formula:
    (4 Radius) / 3 π
    We can align the shape optically with reference to this point;
  • The barycentre for a trapezium is on the straight line joining the centre points of the bases of the trapezium.

The barycentres for more complex or composite shapes require additional calculations. For example, if a shape can be divided into equal sections (such as the previously mentioned diamond shape), then the following rule for finding the barycentre applies:

  • If an icon has a symmetrical axis, its centre of gravity lies on this axis.

The list of formulas for various shapes may be found on this Wikipedia page. So far, we have considered cases of symmetrical shapes and have determined the degree of alignment along one axis. This is half the battle won. However, what should we do if the shape is non-symmetrical?

There are three potential ways to find the barycentre used for most shapes, regardless of symmetry: the geometric breakdown method, the integration method, and finding the barycentre for the final set of coordinates.

In the first case, we break the complex shape down into simpler shapes, and then apply the following formula to calculate the coordinates:

The coordinates of barycentres for simple shapes are designated Gi (for axes X and Y, respectively), while the surface area of the shapes is designated Ai.

However, since we are using graphics editors and plan to automate our solution, it is preferable to avoid breaking the shape down into primitive shapes, avoid taking account of symmetry, and avoid calculating the barycentre of the shape. In this case we can use the integration method:

In this case, g is the characteristic function of the subset, which takes 1 within X and 0 outside it. From this formula we obtain the coordinates along the axis X and Y:

We can simplify the task even further for the purposes of automation, since we always know the coordinate points of the shape that must be aligned, as well as how many there are.

We can find the geometric centre of the shapes as follows: each coordinate of the centre point represents the sum of all values divided by the number of coordinates for the shape along that axis. This approach is more convenient for automation.

This stage yields the basis for the process of automating optical alignment and creating a technical solution. If you only perform this operation occasionally, you can stick to the manual optical alignment method. However, if you are dealing with large numbers of icons and user interface elements, automation is worth considering.

Automate this!

Following on from this approach, I started to search online for solutions and discovered a solution for Adobe Illustrator CS3 based on JavaScript:

/*
JET_Centroid.jsx
A JavaScript for Adobe Illustrator CS3.
Purpose: Finds the centroid (centre of gravity) of selected triangles and other straight-sided multigon paths and draws a user-defined circle at that location.
To Use: Make a selection which includes normal paths. Call the script.

*/
var docRef = activeDocument;
var markerSize = prompt("How large (in points) do you want the centroid marker to be?", 6);
for(s = 0; s < docRef.selection.length; s++){
if(docRef.selection[s].typename == "PathItem"){
var currPath = docRef.selection[s];
var xTotal = 0;
var yTotal = 0;
for (p = 0; p < currPath.pathPoints.length; p++){
var currPoint = currPath.pathPoints[p];
xTotal += currPoint.anchor[0];
yTotal += currPoint.anchor[1];
} //end if for loop
var centroidX = xTotal / currPath.pathPoints.length;
var centroidY = yTotal / currPath.pathPoints.length;
var marker = docRef.pathItems.ellipse(centroidY + (markerSize / 2),centroidX - (markerSize / 2), markerSize, markerSize, 0, 0);
marker.strokeColor = docRef.swatches.getByName("Black").color;
marker.filled = false;
}//end if
}//end for loop

Having studied this solution, I decided to adapt it for Adobe Photoshop — and obtained the following list of steps for determining the geometric centre point:

  1. In Photoshop, centre-align the shapes automatically
  2. In Layers, highlight the Curves layer (Path).
  3. Open the ‘Scripts’ menu.
  4. Select ‘Overview’.
  5. Run GetCentroid.jsx.
  6. The point of intersection between the two directional lines is a reference point for the purposes of alignment; the centre point of the shape should be positioned above its coordinates.

This script performs the following steps:

  1. Reset all coordinates to pixels
  2. Find highlighted layers with curves
  3. Collect coordinates for the points on each layer to create its own JavaScript Object with coordinates for each curve.
  4. Find the surface area for each object.
  5. Find the coordinates of the centroid for each object.
  6. Use the difference between the width of the page and the value along the X axis, and between the height and the value along the Y axis as values for the directional lines.
  7. Invert the guidelines for each axis of coordinates.

This allows you to assess the amount of optical compensation required prior to alignment.

Example of alignment with the help of a script.

You can find out about the script code (and download it) in my repository on GitHub.

A similar script can also be found and applied in other programs or environments. For example, D3, which is JavaScript-based library, already implements a centroid-finding algorithm. You can use procedures similar to those described above in your own code build systems or design systems. You could even write your own alignment algorithm. The key point is that, if you are a software developer, there is no need to align all icons on all your projects manually.

If you don’t want to spend time writing code, there are commercial, ready-to-use plugins and solutions for graphics editors such as the Optically plugin for Sketch.

When should you use Optical Alignment?

The answer to this question depends on how your work is organised.

If you have not yet applied any optical alignment solutions in your working life, it is worth taking a look at the user interfaces you currently work on. You will probably have to correct the alignment for some UI elements.

You can leave this up to the designers, if that option is open to you. In theory this is a possible solution, but in practice the results of the design stage need to be checked at the development stage as well, as user interface elements may need to be optimised for use.

At Badoo, all the images are optimised in advance before icons are developed for user interfaces. We use SVG graphics for our illustrations, icon-sets and native app assets. For our website we use the SVG sprite approach. SVG sprite lines in SVG files are combined into one or more paths when they are created (with more paths being used for more complex icons) and are aligned with their containers. When we prepare icons for SVG sprites we align icons, saving us time and effort without reducing the quality of the user interfaces when we use auto-alignment solutions.

Experience of implementation

At Badoo, we make extensive use of icons in our user interfaces. We show actions, statuses and settings buttons, and links as icons. Icons are commonly arranged into rows, so it is important to ensure that each icon is properly aligned, leading to visual harmony in the way that interfaces are laid out. Optical alignment allows us to maintain balance within the composition of individual icons and rows of icons of a single shape and size.

Let’s say that we have a user interface where three icons arranged in a row. If these icons have the same background and are roughly equal in size and with shapes being strictly (and correctly) aligned, the user interface will look harmonious.

We attempt to maintain this at the development stage by applying optical alignment for frontend developers: we improve the quality of our user interfaces while maintaining clear and predictable estimates of effort and development deadlines.

Optical alignment helps to correct design shortcomings, but it’s by no means a panacea. If basic rules of UI design have been violated during the design stage, frontend developers should not try to fix the problem. That is a different story altogether, and one that is better left to designers alone: e.g., the vertical rhythm of the page and individual sections, or the quality of images used in assets, and so on.

You may encounter a number of limitations in respect of optical alignment:

For example, the algorithm by which icons are smoothed in various browsers. SVG icons contain a vector graphic, which consists of point coordinates and other information relating to shapes and layers. If a shape inside an icon contains points with an odd number of coordinates, it will lead to a noticeable loss of quality affecting the SVG image during alignment. In this case, it is appropriate to correct the dimensions of the icon and its elements. At Badoo we use icons with particular canvas sizes, depending on the type of shape, which helps us to overcome this limitation.

Moreover, there are other unique issues that arise when performing optical alignment with various icons:

  • Subtle elements of the shape or those which extend outside the borders of shape a little, in particular conditions, do not affect the centring of the image (this situation is usually is covered by the script provided);
  • Different shapes in a single colour, when placed vertically on top of each other, will appear to have different colour tone on the monitor screen;
  • Different shapes of a single colour and of identical width/height, but of different shape, will not appear to be aligned with each other by size. For example, any circle will appear smaller next to a square of the same size, so the diameter of the circle must be increased in these circumstances.

A developer can overcome the first limitation acting alone. Other issues, however, fall within the competence of designers. However, when working with user interfaces, a developer should also pay attention to these limitations of optical alignment. This will help to avoid creating extra work in the future when working on the implementation of new user interfaces.

Even aligning icons with other elements of the user interface is often seen as a limitation. If an icon has a single layer and is aligned in relation to its container, it may be placed on a page — with no limitation on the possible context, and where it may be surrounded by elements of various heights and alignments. It might lead to a need for custom alignment, which is highly inadvisable because this breaks patterns, leading to extra work each time certain elements on the page are edited.

In most cases, the user interface has already been designed before the elements enter the development stage. As such, an indication of where all objects should be positioned already exists, with visual consistency and a vertical rhythm for the elements already having been developed.

Comprehensive preparation of the page design can help to avoid these issues and inaccuracies when user interfaces are developed at a later stage; the developer is given a clear idea as to the context of where elements should be positioned on the page and how they should be displayed. As a result, the developer simply has to follow the approved design.

Why is this consideration important to the optical alignment of icons in general? Many companies now have libraries of UI elements and are trying to implement design systems. A library of UI elements represents the individual details of user interfaces outside of the context of a specific page. The fact that this library exists allows you to speed up the development process when using its elements to make new pages. However, when new page designs or design prototypes do not take dimensional grids or the alignment of elements from the library into account, the benefits of this approach no longer apply. Consequently, it is important to avoid this failure by taking a systemic approach when working with design and a library of UI elements. This approach can be summarised as follows:

  1. An element library is created on the basis of the initial design, with information relating to the dimensions and variants of UIelements of user interfaces.
  2. The subsequent page design is based from the element library.
  3. Elements in any new design prototype are aligned with the designs. The dimensions of the lines should not contradict the existing options in the element library (otherwise corrections need to be applied to the library, which adds extra time).
  4. The layout of the icons and the user interfaces should match both the design and the element library.

How to achieve the correct optical alignment in a work context

Optical alignment helps to correct shortcomings that are present in user interfaces, regardless of whether the error occurred during the design stage or the development stage. This method is a litmus test of user interface design: it allows you to assess the quality of the design and the method in a practical context. We should bear this method in mind throughout the design and development phases and when assessing the implementation of the finished UI.

Instead of a conclusion

A good user interface is the result of the work of every single specialist in your team. It is derived from the visual harmony of the creative elements that are rendered on the user’s screen. This harmony can be achieved using various inter-disciplinary knowledge and skills. For example, in our case the intelligent application of geometric approaches and methods in design and development results in algorithms that can achieve optical alignment across multiple elements of a user interface, which helps to enhance the quality standards of user interfaces.

P.S. Attentive readers will note that the diamond-shaped icon is still not aligned. Curiously, this is one of the shapes which is most difficult to align using geometric formulae. However, you can always ask your designer colleagues for help and reach a consensus on optical alignment.

P.P.S. If you are still interested in solving the problem of aligning a diamond icon: you need to sharpen the corners of the diamond, in which case the alignment script yields a good result.

Bumble Tech

This is the Bumble tech team blog focused on technology and…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store