带有FormattedString的Xamarin.Forms标签中的自定义字体

Che*_*2IT 3 xamarin.ios xamarin.android xamarin

我在Android应用中创建了一个自定义LabelRenderer,以在Xamarin Android应用中应用自定义字体(https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/).

对于正常标签而言,一切都很有效,并且内容已添加到.Text属性中.但是,如果我使用.FormattedText属性创建标签,则不会应用自定义字体.

有人做过这样的成功吗?一个选项,因为我只是堆叠不同大小的文本行,是为每个文本使用单独的标签控件,但我更愿意使用格式化的字符串.

这是我的自定义渲染器的胆量:

[assembly: ExportRenderer (typeof (gbrLabel), typeof (gbrLabelRenderer))]

public class gbrLabelRenderer: LabelRenderer
{
    protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged (e);
        var label = (TextView)Control;
        Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, "Lobster-Regular.ttf");
        label.Typeface = font;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的简单标签控件......它所做的只是将字体应用到iOS,并将Android的字体应用到自定义渲染器.

public class gbrLabel: Label
{
    public gbrLabel ()
    {
        Device.OnPlatform (
            iOS: () => {
                FontFamily = "Lobster-Regular";
                FontSize = Device.GetNamedSize(NamedSize.Medium,this);
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

仅适用于具有.Text属性的标签,但不适用于具有.FormattedText属性的标签.

我应该继续挖掘,还是仅仅堆叠我的标签,因为在这种情况下这是一个选项?

以下是我在格式化文本中尝试过的各种方法的示例,因为已请求:

var fs = new FormattedString ();
fs.Spans.Add (new Span { 
    Text = string.Format("LINE 1\n",Title), 
    FontSize = Device.GetNamedSize(NamedSize.Large,typeof(Label))
});
fs.Spans.Add (new Span { 
    Text = string.Format ("LINE 2\n"), 
    FontSize = Device.GetNamedSize(NamedSize.Large,typeof(Label)) * 2,
    FontAttributes = FontAttributes.Bold,
    FontFamily = "Lobster-Regular"
});
fs.Spans.Add (new Span {
    Text = string.Format ("LINE 3\n"),
    FontSize = Device.GetNamedSize(NamedSize.Medium,typeof(Label)),
    FontFamily = "Lobster-Regular.ttf"
});

gbrLabel lblContent = new gbrLabel {
    FormattedText = fs
}
Run Code Online (Sandbox Code Playgroud)

这些(第一个应该由默认的类/渲染器设置,第二个是在包含跨度定义中的字体的变体)在Android上都不起作用.

Sve*_*übe 22

注意: Android和iOS问题已在博客文章中进行了总结:smstuebe.de/2016/04/03/formattedtext.xamrin.forms/


只要您没有设置FontSize或设置字体FontAttributes.所以我看了一下实现,发现FormattedText正在尝试加载字体,就像在Android上无法使用的默认渲染器一样.

android格式化系统的工作方式与Xamarin.Forms非常相似.它使用跨度来定义文本属性.渲染器FontSpan为每个Span自定义字体,大小或属性添加一个.不幸的是,这个FontSpan类是一个私有的内部类,FormattedStringExtensions所以我们必须处理反思.

我们的渲染器正在更新Control.TextFormattedon初始化以及FormattedText属性更改时.在更新方法中,我们获取所有FontSpans并将其替换为我们的CustomTypefaceSpan.

渲染

public class FormattedLabelRenderer : LabelRenderer
{
    private static readonly Typeface Font = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Regular.ttf");
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        Control.Typeface = Font;
        UpdateFormattedText();
    }

    private void UpdateFormattedText()
    {
        if (Element.FormattedText != null)
        {
            var extensionType = typeof(FormattedStringExtensions);
            var type = extensionType.GetNestedType("FontSpan", BindingFlags.NonPublic);
            var ss = new SpannableString(Control.TextFormatted);
            var spans = ss.GetSpans(0, ss.ToString().Length, Class.FromType(type));
            foreach (var span in spans)
            {
                var start = ss.GetSpanStart(span);
                var end = ss.GetSpanEnd(span);
                var flags = ss.GetSpanFlags(span);
                var font = (Font)type.GetProperty("Font").GetValue(span, null);
                ss.RemoveSpan(span);
                var newSpan = new CustomTypefaceSpan(Control, font);
                ss.SetSpan(newSpan, start, end, flags);
            }
            Control.TextFormatted = ss;
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == Label.FormattedTextProperty.PropertyName)
        {
            UpdateFormattedText();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定,为什么你引入了一个新的元素类型gbrLabel,但只要你不想改变渲染器,你就不必创建一个自定义元素.您可以替换默认元素的渲染器:

[assembly: ExportRenderer(typeof(Label), typeof(FormattedLabelRenderer))]
Run Code Online (Sandbox Code Playgroud)

CustomTypefaceSpan

public class CustomTypefaceSpan : MetricAffectingSpan
{
    private readonly Typeface _typeFace;
    private readonly Typeface _typeFaceBold;
    private readonly Typeface _typeFaceItalic;
    private readonly Typeface _typeFaceBoldItalic;
    private readonly TextView _textView;
    private Font _font;

    public CustomTypefaceSpan(TextView textView, Font font)
    {
        _textView = textView;
        _font = font;
        // Note: we are ignoring _font.FontFamily (but thats easy to change)
        _typeFace = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Regular.ttf");
        _typeFaceBold = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Bold.ttf");
        _typeFaceItalic = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-Italic.ttf");
        _typeFaceBoldItalic = Typeface.CreateFromAsset(Forms.Context.Assets, "LobsterTwo-BoldItalic.ttf");
    }

    public override void UpdateDrawState(TextPaint paint)
    {
        ApplyCustomTypeFace(paint);
    }

    public override void UpdateMeasureState(TextPaint paint)
    {
        ApplyCustomTypeFace(paint);
    }

    private void ApplyCustomTypeFace(Paint paint)
    {
        var tf = _typeFace;

        if (_font.FontAttributes.HasFlag(FontAttributes.Bold) && _font.FontAttributes.HasFlag(FontAttributes.Italic))
        {
            tf = _typeFaceBoldItalic;
        }
        else if (_font.FontAttributes.HasFlag(FontAttributes.Bold))
        {
            tf = _typeFaceBold;
        }
        else if (_font.FontAttributes.HasFlag(FontAttributes.Italic))
        {
            tf = _typeFaceItalic;
        }

        paint.SetTypeface(tf);
        paint.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Sp, _font.ToScaledPixel(), _textView.Resources.DisplayMetrics);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们的自定义CustomTypefaceSpan类似于FontSpanXamarin.Forms,但是加载自定义字体并且可以为不同的字体加载不同的字体FontAttributes.

结果是一个漂亮的彩色文字:) 在此输入图像描述