我有一个带有格式化文本的标签,我想改变它的字体样式(我的意思是字体)。 我尝试使用自定义标签渲染(就像为普通文本做的那样),但它没有得到反映。 我怀疑的是我们是否可以更改格式化文本的字体(因为它适用于标签的文本(非格式化文本))。
这是我的.xaml文件代码
<Label x:Name = "invosTitle" Grid.Column = "0" Grid.Row = "0" Grid.ColumnSpan = "3" HorizontalOptions = "CenterAndExpand">
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text = "abcd" ForegroundColor = "White" ></Span>
<Span Text = " "></Span>
<Span Text = "efgh" ForegroundColor = "Gray"></Span>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
和CustomLabelRenderer代码是
protected override void OnElementPropertyChanged (object sender , PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var label = (TextView)Control;
Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, "Fonts/microsoftjhengheibold.otf");
label.Typeface = font;
label.SetTypeface (font, TypefaceStyle.Bold);
}
答案 0 :(得分:2)
使用FormattedString元素时,您可以使用Span
属性单独更改每个FontFamily
的字体。您不需要自定义标签渲染器来实现此目的。
<Span Text="abcd"
ForegroundColor="White"
FontFamily="Helvetica" />
Xamarin "Working with fonts"文档中记录了这一点。
答案 1 :(得分:0)
万一有人需要保持相同的字体,只需更改跨度颜色代码:
[assembly: ExportRenderer (typeof (Label), typeof (LabelCustomRenderer))]
namespace YourNamespace
{
public class LabelCustomRenderer : LabelRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
{
base.OnElementChanged (e);
Init ();
}
protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (e.PropertyName == Label.FontFamilyProperty.PropertyName) {
Init ();
}
}
void Init(){
if (Control != null) {
var label = (CustomLabel)Element;
if (label.FontName != null) {
if (label.FormattedText != null) {
SpannableStringBuilder ssb = new SpannableStringBuilder ();
foreach (Span span in label.FormattedText.Spans) {
ssb.Append (span.Text);
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan (span.ForegroundColor.ToAndroid ());
ssb.SetSpan (foregroundColorSpan, ssb.Length () - span.Text.Length, ssb.Length (), SpanTypes.ExclusiveExclusive);
}
Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, "Fonts/" + label.FontFamily);
Control.Typeface = font;
Control.TextSize = (float)label.FontSize;
Control.SetText (ssb, TextView.BufferType.Normal);
} else {
Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, "Fonts/" + label.FontFamily);
Control.Typeface = font;
Control.TextSize = (float)label.FontSize;
}
}
}
}
}
}