devxlogo

Text Rendering with Xamarin

Text Rendering with Xamarin

One of the most important aspects of mobile programming is displaying text on the screen. The relatively limited real estate of the mobile phone means that in order to provide a superb user experience, you have to consider very carefully how much information to present to the user in each moment and how to balance text with other elements. In this article I’ll use C#, XAML and Xamarin to explore several possibilities of rendering text to the screen.

XAML

Xamarin supports XAML (Extensible Application Markup Language), which originated with the WPF (Windows Presentation Framework). It is a declarative XML dialect to describe your application UI. It is very concise and readable way to describe any static aspects of your user interface that you don’t need to modify dynamically. Xamarin, of course, supports full programmatic access to the UI, so you can access the existing UI describe by XAML and modify it on the fly. Here is the XAML “Hello world!”:

    

There is also a code behind file that looks like this:

using Xamarin.Forms;namespace TextRenderer{    public partial class TextRendererPage : ContentPage    {        public TextRendererPage ()        {            InitializeComponent ();        }    }}

Here is what it looks like:

The Label Control

Notice that the “Hello world!” text is enclosed in a “Label” element. If you come from a WPF background you may be familiar with the WPF Label and TextBlock. In Xamarin there is just Label. As you will soon discover, it is very powerful.

Controlling Text Appearance

You can control many aspects of the way the text is rendered on the screen. The label (or its ancestors in the class hierarchy) provide attributes such as TextColor, BackgroundColor, FontAttributes, FontSize and FontFamily (don’t use the deprecated Font). Let’s see those in action.

Here is the result:

Multi-style Text

This is very cool, but what if you want to have different attributes for different words or expressions? Have no fear. The Label has in addition to the Text attribute also a FormattedText attribute that can hold multiple Span objects. Each one of these Span objects has the same attributes as a Label. Let’s see it in action.

There is a lot going on here. The label has a FormattedText attribute (note the syntax for attribute that are XAML elements). The FormattedText attribute contains a FormattedString that contains Spans that contain a list of Span objects that have their own text and styling options. The first Span has a Text attribute that contains two lines. The other Span objects have just a single line. Each Span object has its own font size and foreground color.

Here is what it looks like:

Even ignoring the horrendous colors and the terrible joke, it looks really messy with the spans just smashed together. Let’s see how to improve it programmatically. This code goes in the App.xaml.cs file:

using Xamarin.Forms;using System;namespace TextRenderer{    public partial class App : Application    {        public App ()        {            // paragraph of weird text with even weirder formatting            var joke = new FormattedString ();            var lines = new [] {                new { Text = "Knock Knock!", ForegroundColor = Color.Red, FontSize = 10},                new { Text = "Who're there?", ForegroundColor = Color.Blue, FontSize = 20 },                new { Text = "Boo", ForegroundColor = Color.Green, FontSize = 30},                new { Text = "Boo who?", ForegroundColor = Color.Yellow, FontSize = 20},                new { Text = "Don't cry. It's only a knock-knock joke.", ForegroundColor = Color.Purple, FontSize = 10}            };            foreach (var line in lines) {                joke.Spans.Add (new Span {                    Text = line.Text + Environment.NewLine,                    FontSize = line.FontSize,                    ForegroundColor = line.ForegroundColor                });            }            var jokeLabel = new Label {                HorizontalTextAlignment = TextAlignment.Center,                VerticalOptions = LayoutOptions.Center,                BackgroundColor = Color.Gray,                FormattedText = joke            };            // The root page of your application            MainPage = new ContentPage {                Content = jokeLabel            };        }        protected override void OnStart ()        {            // Handle when your app starts        }        protected override void OnSleep ()        {            // Handle when your app sleeps        }        protected override void OnResume ()        {            // Handle when your app resumes        }    }}

Now, each joke line shows up on a separate line on the screen:

Text Placement

Now, that you know how to manipulate the text within the label you need to understand how to place it on the screen and how to align the text within the label. The HorizontalOptions and VerticalOptions control the position of the label within its container. There are several values: Start, Center, End, StartAndExpand, EndAndExpand. Start means left for horizontal and top for vertical. End means right for horizontal and bottom for vertical. The …AndExpand options apply only when the label is placed inside of a stack layout. In which case, it will take all remaining space.

To align text within the label you can use the HorizontalTextAlignment and VerticalTextAlignment attributes. The default is Center. For example, to display our joke aligned to the left the only change needed is:

HorizontalTextAlignment = TextAlignment.Start

Here is the result:

Conclusion

Xamarin provides a strong text rendering engine powered by both declarative XAML as well as programmatic access via C#. The Label component is the workhorse for rendering read-only text. It combines the capabilities of the Label and TextBlock from WPF.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist