Press "Enter" to skip to content

Adding Kerning to Labels in Xamarin Forms

Adding Kerning to your Labels in Xamarin Forms

When we have a design using letters with more/less spacing that expected, this technique is called kerning which is the process of adding or substract space between characters.

In this article I’m going to show you how to add it to Xamarin Forms labels.

To achieve it we will start creating a custom Label with a property to set the spacing:

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace CustomKerningSample.Controls
{
    public class CustomLabel : Label
    {
        public static readonly BindableProperty KerningProperty = BindableProperty.Create(
           propertyName: nameof(Kerning),
           returnType: typeof(float),
           declaringType: typeof(CustomLabel),
           defaultValue: 0.0f,
           defaultBindingMode: BindingMode.TwoWay);

        public float Kerning
        {
            get { return (float)GetValue(KerningProperty); }
            set { SetValue(KerningProperty, value); }
        }
    }
}

iOS

On iOS project we are going to create a custom renderer. To achieve it in iOS is really easy, the UILabels has a property called AttributedText which has an attribute called KerningAdjustment, in this attribute we are going to set the spacing we set in the control.

Android

On Android project we are going to create a custom renderer as well. To achieve it in Android is more difficult than iOS because is not just assigning a property, instead we are going to play with the StringBuilder adding non-breaking space and with the SpannableString setting an ScaleXSpan per each string letter.

XAML

And now we can use our control like this:

 <controls:CustomLabel Text="Hello" 
                              HorizontalTextAlignment="Center"
                              HorizontalOptions="FillAndExpand"
                              x:Name="element"/>

Full source code here:

https://github.com/rdelrosario/CustomKerningSample

Happy kerning!

Reference
https://helpx.adobe.com/in/indesign/how-to/adjust-letter-spacing.html
http://devsign.co/notes/tracking-and-character-spacing
https://gist.github.com/SyllaJay/18674eab213b2fe90a2a