2016-11-28 59 views
1

正如標題所述,我需要在Assets中使用帶有自定義字體的TypefaceSpan對象,但我無法找到實現此目的的正確方法。 字體的文件是「HelveticaNeueLTCom-BdCn.ttf」Xamarin Android TypefaceSpan在Assets文件夾中具有自定義字體

這是我的兩個嘗試這並沒有爲我工作:

// first attempt 
var textViewTitle = new TextView(Context); 
var span = new SpannableString("MyLongTitle"); 
span.SetSpan(new TypefaceSpan("HelveticaNeueLTCom-BdCn.ttf"), 0, 5, SpanTypes.ExclusiveExclusive); 
textViewTitle.TextFormatted = span; 


// second attempt 
var textViewTitle = new TextView(Context); 
var span = new SpannableString("MyLongTitle"); 
span.SetSpan(new Typeface(Typeface.CreateFromAsset(Context.Assets, "fonts/HelveticaNeueLTCom-BdCn.ttf")), 0, 5, SpanTypes.ExclusiveExclusive); 
textViewTitle.TextFormatted = span; 

任何人有一些提示或建議?

回答

1

差不多一年後,我面臨同樣的問題,我找到了實現它的方法。

我看到您在Xamarin論壇here中發佈了相同的問題,但您在回答中寫入的鏈接已損壞。不過,我認爲這是幫助你的this post,因爲它幫助了我。 所以這裏走的路。

首先創建一個自定義TypefaceSpan這樣

using System; 
using Android.OS; 
using Android.Runtime; 
using Android.Text.Style; 
using Android.Graphics; 
using Android.Text; 

namespace Droid.Spans 
{ 
    public class CustomTypefaceSpan : TypefaceSpan 
    { 
    private readonly Typeface _typeface; 

    public CustomTypefaceSpan(Typeface typeface) 
    : base(string.Empty) 
    { 
     _typeface = typeface; 
    } 
    public CustomTypefaceSpan(IntPtr javaReference, JniHandleOwnership transfer) 
     : base(javaReference, transfer) 
    { 
    } 
    public CustomTypefaceSpan(Parcel src) 
    : base(src) 
    { 
    } 
    public CustomTypefaceSpan(string family) 
    : base(family) 
    { 
    } 
    public override void UpdateDrawState(TextPaint ds) 
    { 
     ApplyTypeface(ds, _typeface); 
    } 
    public override void UpdateMeasureState(TextPaint paint) 
    { 
     ApplyTypeface(paint, _typeface); 
    } 
    private static void ApplyTypeface(Paint paint, Typeface tf) 
    { 
     paint.SetTypeface(tf); 
    } 
    } 
} 

然後用這個CustomTypefaceSpan的跨度添加到SpannableString

var spannableString = new SpannableString("Anything to write with a special font"); 
spannableString.SetSpan(new CustomTypefaceSpan(Typeface.CreateFromAsset(Assets, "HelveticaNeueLTCom-BdCn.ttf"), 0, 7, SpanTypes.InclusiveInclusive); 
textView.TextFormatted = spannableString; 
相關問題