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.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists