Xamarin形式:标签文本中的字母间距 [英] Xamarin Forms: Letter spacing in Label Text

查看:143
本文介绍了Xamarin形式:标签文本中的字母间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xamarin表单PCL构建跨平台应用程序.在该应用中,我需要为标签文本添加字母间距. 标签文本字符之间需要空格.有没有办法为所有平台实现这一目标. Letterspacing属性在ANDROID中可用,但我需要适用于ios,uwp,win8/8.1等所有平台的解决方案.

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.

推荐答案

表单控件

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

Android渲染器代码如下:

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渲染器

    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;
    }

下面的代码示例演示如何使用 LetterSpacingLabel 控件:

The following code example demonstrates using the LetterSpacingLabel control:

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

以下屏幕截图显示了 iOS

来自帖子此处

这篇关于Xamarin形式:标签文本中的字母间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆