Last active
February 15, 2016 10:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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