Skip to content

Instantly share code, notes, and snippets.

@sthewissen
Last active February 15, 2016 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sthewissen/217ce180f2b7532c0546 to your computer and use it in GitHub Desktop.
Save sthewissen/217ce180f2b7532c0546 to your computer and use it in GitHub Desktop.
Renders a label using a custom font, as described @ http://bit.ly/20yzZ7i
using System;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using Android.Graphics;
[assembly:ExportRenderer(typeof(Label), typeof(CustomFontLabelRenderer))]
namespace CustomXamFormsFont.Droid
{
public class CustomFontLabelRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (!string.IsNullOrEmpty(e.NewElement?.FontFamily))
{
try
{
var font = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, e.NewElement.FontFamily + ".ttf");
Control.Typeface = font;
}
catch(Exception ex)
{
// An exception means that the custom font wasn't found.
// Typeface.CreateFromAsset throws an exception when it didn't find a matching font.
// When it isn't found we simply do nothing, meaning it reverts back to default.
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment