In Xamarin.Forms
using a glyph from a
Export the font:
[assembly: ExportFont("smiley.ttf", Alias = "smiley")]
Use the glyph in xaml
for the Text
property:
<StackLayout BackgroundColor="#eeeeee">
<!--Uses glyph #E800 from smiley.ttf-->
<Button BorderColor="Aqua"
BackgroundColor="Yellow"
BorderWidth="5"
CornerRadius="10"
FontSize="150"
FontFamily="smiley"
Text=""
TextColor="Black"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"
HeightRequest="200"
WidthRequest="200" />
</StackLayout>
I would like to do the same thing in Winforms
. Here's what I tried:
public MainForm()
{
InitializeComponent();
// For the sake of simplicity, the TTF is copied to output directory...
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Fonts", "smiley.ttf");
// ... and loaded here.
privateFontCollection.AddFontFile(path);
var fontFamily = privateFontCollection.Families[0];
Debug.Assert(fontFamily.Name == "smiley", "Expecting 'smiley' is the font family name");
button1.Font = new Font(fontFamily, 12F);
button1.UseCompatibleTextRendering = true;
// Shows 'A'
// button1.Text = "A";
// Shows nothing.
button1.Text = "\u0E00";
}
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
Is such a thing even possible? I tried various settings of button1.UseCompatibleTextRendering = true
and Application.SetCompatibleTextRenderingDefault(true)
without success.
CodePudding user response:
The answer to the question: Can Fontello glyph be used for Winforms button in a similar way as for a Xamarin Forms button? is YES.
Thanks to Jimi for the comment pointing out my typo, and also for mentioning the necessity of disposal which I was also not aware of.
Here is the working code:
public partial class MainForm : Form
{
// https://stackoverflow.com/a/36509042/5438626
// https://docs.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-create-a-private-font-collection?view=netframeworkdesktop-4.8
public MainForm()
{
InitializeComponent();
// For the sake of simplicity, the TTF is copied to output directory...
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Fonts", "smiley.ttf");
// ... and loaded here.
privateFontCollection.AddFontFile(path);
var fontFamily = privateFontCollection.Families[0];
Debug.Assert(fontFamily.Name == "smiley", "Expecting 'smiley' is the font family name");
button1.Font = new Font(fontFamily, 12F);
button1.UseCompatibleTextRendering = true;
button1.Text = "\uE800";
button1.BackColor = Color.Yellow;
}
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
privateFontCollection.Dispose();
}
base.Dispose(disposing);
}
}