Xamarin Forms: Letter spacing in Label Text

十年热恋 提交于 2019-12-23 12:34:02

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/41447049/xamarin-forms-letter-spacing-in-label-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!