Eventos

[Xamarin] Fuentes personalizadas en aplicaciones Xamarin.Forms


Para el presente post usaré 2 fuentes (Magistral.otf y RadicalBeat.ttf) y quiero hacer recordar que para conocer el nombre de una fuente hay que darle doble click al archivo .otf o .ttf.

PCL

Creamos un control personalizado extendiendo la clase Label para disponer de una propiedad FontName.

using Xamarin.Forms;
namespace _20160228.Controls
{
public class AppLabel : Label
{
public static readonly BindableProperty FontNameProperty =
BindableProperty.Create<AppLabel, string>(
p => p.FontName, null, BindingMode.TwoWay);
public string FontName
{
get
{
return (string)GetValue(FontNameProperty);
}
set
{
SetValue(FontNameProperty, value);
}
}
}
}
view raw AppLabel.cs hosted with ❤ by GitHub

Definimos una interfaz gráfica sin olvidarnos de importar el namespace de nuestro control personalizado.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:_20160228.Controls"
x:Class="_20160228.Views.MainPage">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<Label Text="Magistral" FontSize="Large"/>
<controls:AppLabel Text="Reach" FontSize="Small" FontName="MagistralC"/>
<controls:AppLabel Text="Reach" FontSize="Medium" FontName="MagistralC"/>
<controls:AppLabel Text="Reach" FontSize="Large" FontName="MagistralC"/>
<Label Text="Radical Beat" FontSize="Large"/>
<controls:AppLabel Text="Reach" FontSize="Small" FontName="Radical Beat"/>
<controls:AppLabel Text="Reach" FontSize="Medium" FontName="Radical Beat"/>
<controls:AppLabel Text="Reach" FontSize="Large" FontName="Radical Beat"/>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub

iOS

Establecemos el Build Action de las fuentes en BundleResource y el Copy to Output Directory en Copy always.


Luego modificamos el Info.plist para indicar en donde se encuentran nuestras fuentes.


Creamos una clase que extienda de LabelRenderer.

using _20160228.Controls;
using _20160228.iOS.Renderers;
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(AppLabel), typeof(AppLabelRenderer))]
namespace _20160228.iOS.Renderers
{
public class AppLabelRenderer : LabelRenderer
{
public AppLabelRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (null != Control)
{
var fontName = ((AppLabel)e.NewElement).FontName;
Control.Font = TryGetFont(fontName, (float)e.NewElement.FontSize);
}
}
private UIFont TryGetFont(string fontName, float fontSize)
{
try
{
return UIFont.FromName(fontName, fontSize);
}
catch (Exception)
{
var defaultFontName = UIFont.FontNamesForFamilyName(UIFont.FamilyNames[0])[0];
return UIFont.FromName(defaultFontName, fontSize);
}
}
}
}

Y listo.


Android

Establecemos el Build Action de las fuentes en AndroidAsset.


Creamos una clase que extienda de LabelRenderer.

using _20160228.Controls;
using _20160228.Droid.Renderers;
using Android.Graphics;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(AppLabel), typeof(AppLabelRenderer))]
namespace _20160228.Droid.Renderers
{
public class AppLabelRenderer : LabelRenderer
{
public AppLabelRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (null != Control)
{
var fontName = ((AppLabel)e.NewElement).FontName;
Control.Typeface = TryGetFont(fontName);
}
}
private Typeface TryGetFont(string fontName)
{
try
{
if (fontName == "MagistralC")
return Typeface.CreateFromAsset(Forms.Context.Assets, "MagistralC.otf");
if (fontName == "Radical Beat")
return Typeface.CreateFromAsset(Forms.Context.Assets, "RadicalBeat.ttf");
else
return Typeface.Default;
}
catch (Exception)
{
return Typeface.Default;
}
}
}
}

Y listo.


Los gists usados para este post puedes ubicarlos aqu&iacute: https://gist.github.com/MAlexanderSalazar/62bdf1ac153078817b26

1 comentario:

Epicalsoft — Superheroic Software Development Blog Designed by Templateism Copyright © 2014

Con tecnología de Blogger.