How can I use TypefaceSpan or StyleSpan with a custom Typeface?

后端 未结 5 2030
北恋
北恋 2020-11-22 14:59

I have not found a way to do this. Is it possible?

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 15:53

    If anybody would be interested here's C# Xamarin version of Benjamin's code:

    using System;
    using Android.Graphics;
    using Android.Text;
    using Android.Text.Style;
    
    namespace Utils
    {
        //https://stackoverflow.com/a/17961854/1996780
        /// A text span which applies  on text
        internal class CustomFontSpan : MetricAffectingSpan
        {
            /// The typeface to apply
            public Typeface Typeface { get; }
    
            /// CTor - creates a new instance of the  class
            /// Typeface to apply
            ///  is null
            public CustomFontSpan(Typeface typeface) =>
                Typeface = typeface ?? throw new ArgumentNullException(nameof(typeface));
    
    
            public override void UpdateDrawState(TextPaint drawState) => Apply(drawState);
    
            public override void UpdateMeasureState(TextPaint paint) => Apply(paint);
    
            /// Applies 
            ///  to apply  on
            private void Apply(Paint paint)
            {
                Typeface oldTypeface = paint.Typeface;
                var oldStyle = oldTypeface != null ? oldTypeface.Style : 0;
                var fakeStyle = oldStyle & Typeface.Style;
    
                if (fakeStyle.HasFlag(TypefaceStyle.Bold))
                    paint.FakeBoldText = true;
    
                if (fakeStyle.HasFlag(TypefaceStyle.Italic))
                    paint.TextSkewX = -0.25f;
    
                paint.SetTypeface(Typeface);
            }
        }
    }
    

    And usage: (in activity OnCreate)

    var txwLogo = FindViewById(Resource.Id.logo);
    var font = Resources.GetFont(Resource.Font.myFont);
    
    var wordtoSpan = new SpannableString(txwLogo.Text);
    wordtoSpan.SetSpan(new CustomFontSpan(font), 6, 7, SpanTypes.InclusiveInclusive); //One caracter
    txwLogo.TextFormatted = wordtoSpan;  
    

提交回复
热议问题