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

标签 xamarin xamarin.ios xamarin.android

我在我的 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;
    }
}

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

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

适用于仅具有 .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
}

这些(第一个应该由默认类/渲染器设置,第二个是在跨度定义本身中包含字体的变体)都不能在 Android 上运行。

最佳答案

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

只要不设置FontSize就设置字体或 FontAttributes .所以我查看了实现,发现 FormattedText正在尝试像在 Android 上不起作用的默认渲染器一样加载字体。

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

我们的渲染器正在更新 Control.TextFormatted在初始化和 FormattedText 时属性变化。在更新方法中,我们得到所有 FontSpan s 并将它们替换为我们的 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();
        }
    }
}

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

[assembly: ExportRenderer(typeof(Label), typeof(FormattedLabelRenderer))]

自定义字体跨度

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

我们的定制CustomTypefaceSpan类似于 FontSpan Xamarin.Forms,但正在加载自定义字体,并且可以为不同的 FontAttributes 加载不同的字体.

结果是一个漂亮的彩色文本:)
enter image description here

关于xamarin - 带有 FormattedString 的 Xamarin.Forms 标签中的自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223519/

相关文章:

android - 如何Mvvm交叉绑定(bind)drawableId到Imageview

c# - xamarin 上的 HttpClient PostAsync 什么都不做

iphone - 在monotouch中使用iphone Objective-C代码的现有代码(monotouch iphone中的范围 slider )

c# - monodroid 中的 DataAnnotations

c# - 绑定(bind)到 Entry.Text 的属性 setter 无限循环

ios - Xamarin iOS 项目引用绑定(bind)在 sim 上而不是在设备上启动

ios - UITabBarController 等待加载 UIViewController 直到选择 Xamarin

ios - BecomeFirstResponder() 不适用于 UITextField

c# - 错误 native 链接错误 : framework not found IOSurface for architecture arm64

android - 无法在 Xamarin Android 中将应用程序主题设置为 Theme.Material