Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Text Rendering with Xamarin

One of the most important aspects of mobile development is displaying text on the screen. Get some tips on how to use C#, XAML and Xamarin to explore several possibilities of rendering text to the screen.


advertisement

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!":

<?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:local="clr-namespace:TextRenderer" 
             x:Class="TextRenderer.TextRendererPage">
    <Label Text="Hello world!" 
           VerticalOptions="Center" 
           HorizontalOptions="Center"" FontSize="8" />
</ContentPage>


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.

<?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:local="clr-namespace:TextRenderer" 
             x:Class="TextRenderer.TextRendererPage">
<Label 
Text="Hello world!" 
FontSize="Micro"
FontFamily="Arial"
FontAttributes="Italic" 
TextColor="Red"
BackgroundColor="Lime"
VerticalOptions="Center" 
HorizontalOptions="Center"
/>
</ContentPage>

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.

<?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:local="clr-namespace:TextRenderer" x:Class="TextRenderer.TextRendererPage">
<Label 
FontSize="Micro"
BackgroundColor="Gray"
VerticalOptions="Center" 
HorizontalOptions="Start"
>
<Label.FormattedText>
       <FormattedString>
           <FormattedString.Spans>
               <Span ForegroundColor="Red" FontSize="10">
<Span.Text>
Knock Knock!
Who's there?
</Span.Text>
</Span>
               <Span Text="Boo " ForegroundColor="Green" FontAttributes="Bold" FontSize="30"/>
<Span Text="Boo Who? " ForegroundColor="Yellow" FontAttributes="Italic,Bold" FontSize="20"/>
<Span Text="Don't cry. It's only a knock-knock joke." ForegroundColor="Purple" FontSize="10"/>
           </FormattedString.Spans>
       </FormattedString>
   </Label.FormattedText>
</Label>
</ContentPage>

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.



   
Gigi Sayfan is the chief platform architect of VRVIU, a start-up developing cutting-edge hardware + software technology in the virtual reality space. Gigi has been developing software professionally for 21 years in domains as diverse as instant messaging, morphing, chip fabrication process control, embedded multi-media application for game consoles, brain-inspired machine learning, custom browser development, web services for 3D distributed game platform, IoT/sensors and most recently virtual reality. He has written production code every day in many programming languages such as C, C++, C#, Python, Java, Delphi, Javascript and even Cobol and PowerBuilder for operating systems such as Windows (3.11 through 7), Linux, Mac OSX, Lynx (embedded) and Sony Playstation. His technical expertise includes databases, low-level networking, distributed systems, unorthodox user interfaces and general software development life cycle.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date