Xamarin Forms: Letter spacing in Label Text

labelportable-class-libraryxamarin.forms

Hi I am building an cross platform app using Xamarin forms PCL. In that app I need to add letter spacing to label text.
I need space between label text characters. Is there any way to achieve this for all platforms. Letterspacing property is available in ANDROID but I need solution for all the platforms like ios, uwp, win8/8.1.

Best Answer

Forms control

public class LetterSpacingLabel : Label
{
    public float LetterSpacing { get; set; }
}

The Android renderer code looks like:

public class LetterSpacingLabelRenderer : LabelRenderer
{
    protected LetterSpacingLabel LetterSpacingLabel { get; private set; }

    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement == null)
        {
            this.LetterSpacingLabel = (LetterSpacingLabel)this.Element;
        }

        var letterSpacing = this.LetterSpacingLabel.LetterSpacing;
        this.Control.LetterSpacing = letterSpacing;

        this.UpdateLayout();
    }
}

iOS renderer

    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        var data = Element as LetterSpacingLabel;
        if (data == null || Control == null)
        {
            return;
        }

        var text = Control.Text;
        var attributedString = new NSMutableAttributedString(text);

        var nsKern = new NSString("NSKern");
        var spacing = NSObject.FromObject(data.LetterSpacing * 10);
        var range = new NSRange(0, text.Length);

        attributedString.AddAttribute(nsKern, spacing, range);
        Control.AttributedText = attributedString;
    }

The following code example demonstrates using the LetterSpacingLabel control:

< LetterSpacingLabel LetterSpacing="0.5" Text="Lorem ipsum dolor sit amet" />

The following screenshot show the label on iOS

From post here

Related Topic