Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms: Letter spacing in Label Text

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.

like image 884
Sonali Avatar asked Jan 03 '17 15:01

Sonali


People also ask

What is padding in Xamarin?

The Padding property represents the distance between an element and its child elements, and is used to separate the control from its own content. Padding values can be specified on layout classes.

How do I bold a label in Xamarin?

By default, Xamarin. Forms uses a system font defined by each platform. However, controls that display text define properties that you can use to change this font: FontAttributes , of type FontAttributes , which is an enumeration with three members: None , Bold , and Italic .


1 Answers

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

like image 109
Anastasia Avatar answered Oct 03 '22 15:10

Anastasia