Tag Archives: Xamarin Forms Label

Fancy Me! Here’s a Label with Rounded Corners in Xamarin Forms…

Time for something fancy, a Label with Rounded corners in Xamarin Forms! 😉

Why you’d ask? Well why not!

Sneak peak…

screenshot-1

Well look how cool that is yeah. So let’s see how we could do this.

Let the coding begin…

So as usual let’s sub-class our custom Label from the default Xamarin Forms Label control.

namespace WhateverYourNamespace
{
    public class CurvedCornersLabel : Label
    {
        ...
    }
}

 

some custom properties?

Yep we are going to be needing some custom properties to define the Radius value for the corners of the Label and then the background color for the Curved background, well of course you could use the default BackgroundColor property, but where’s the fun in that? lol 😛

public static readonly BindableProperty CurvedCornerRadiusProperty =
	BindableProperty.Create(
		nameof(CurvedCornerRadius),
		typeof(double),
		typeof(CurvedCornersLabel),
		12.0);
public double CurvedCornerRadius
{
	get { return (double)GetValue(CurvedCornerRadiusProperty); }
	set { SetValue(CurvedCornerRadiusProperty, value); }
}


public static readonly BindableProperty CurvedBackgroundColorProperty =
	BindableProperty.Create(
		nameof(CurvedCornerRadius),
		typeof(Color),
		typeof(CurvedCornersLabel),
		Color.Default);
public Color CurvedBackgroundColor
{
	get { return (Color)GetValue(CurvedBackgroundColorProperty); }
	set { SetValue(CurvedBackgroundColorProperty, value); }
}

 

Now add the above properties inside the Custom control we just created above. As you can see as the default Radius we are setting value 12, if no explicit values were given this will be set as the corner radius of the Label. 🙂

Android stuff…

Let’s dig into the Android Renderer for our fancy Label 😉

So the Android TextView, which is the native control that corresponds with Xamarin Forms Label at run time,  doesn’t have a corner radius property.

So in order to create a Curved background in TextView we need to add Background Drawable layer.

Preferably a GradientDrawable which has the CornerRadius property where we could use to manipulate the curved corners as the background for our Label. Perfecto!

[assembly: ExportRenderer(typeof(CurvedCornersLabel), typeof(CurvedCornersLabelRenderer))]
namespace WhateverYourNamepsace.Droid
{
public class CurvedCornersLabelRenderer : LabelRenderer
{
	private GradientDrawable _gradientBackground;

	protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
	{
		base.OnElementChanged(e);

		var view = (CurvedCornersLabel)Element;
		if (view == null) return;

		// creating gradient drawable for the curved background
		_gradientBackground = new GradientDrawable();
		_gradientBackground.SetShape(ShapeType.Rectangle);
		_gradientBackground.SetColor(view.CurvedBackgroundColor.ToAndroid());
		
		// Thickness of the stroke line
		_gradientBackground.SetStroke(4, view.CurvedBackgroundColor.ToAndroid());
		
		// Radius for the curves
		_gradientBackground.SetCornerRadius(
			DpToPixels(this.Context,
			Convert.ToSingle(view.CurvedCornerRadius)));

		// set the background of the label
		Control.SetBackground(_gradientBackground);
	}

	/// <summary>
	/// Device Independent Pixels to Actual Pixles conversion
	/// </summary>
	/// <param name="context"></param>
	/// <param name="valueInDp"></param>
	/// <returns></returns>
	public static float DpToPixels(Context context, float valueInDp)
	{
		DisplayMetrics metrics = context.Resources.DisplayMetrics;
		return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
	}
}
}

 

So there you have it, we create a Drawable object with the Rectangle shape, and then we set the required properties such as Stroke Color and Corner Radius.

Now you may have noticed that I’m using exact Pixel values for the Radius value from the DpToPixels() method, this is to ensure the Radius value supports as many devices as possible without distorting the expected curve shape. And if you read my previous post, I have already talked about Device Independent Pixels and actual Device Pixels: DpToPixels and PixelsToDp for Xamarin Android…

Once the Drawable object is configured, we set it as the Background of the Label 🙂

iOS stuff…

Next is the iOS renderer for our control.

For iOS we have the UILabel that corresponds with the Xamarin Forms Label control at run time, now for the luck of it UILabel already has a property that associates with Radius of the corners, via the Layer property. So we could directly render the curved corners through those properties.

[assembly: ExportRenderer(typeof(CurvedCornersLabel), typeof(CurvedCornersLabelRenderer))]
namespace WhateverYourNamepsace.iOS
{ 
    public class CurvedCornersLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                var _xfViewReference = (CurvedCornersLabel)Element;
				
		// Radius for the curves
                this.Layer.CornerRadius = (float)_xfViewReference.CurvedCornerRadius;
				
                this.Layer.BackgroundColor = _xfViewReference.CurvedBackgroundColor.ToCGColor();
            }
        }
    }
}

 

There we go, we set the Layer’s CornerRadius property with our CurvedCornerRadius value and the background color to the Layer.

Let’s try it out…

Now let’s consume this sweetness…

<StackLayout VerticalOptions="CenterAndExpand">

	<Label
	  Text="this is a normal Label"
	  HorizontalTextAlignment="Center"
	  VerticalTextAlignment="Center"
	  FontSize="14.5"
	  HeightRequest="30"
	  BackgroundColor="#20a9f8"
	  TextColor="White"/>

	<local:CurvedCornersLabel
	  Text="this is a rounded Label"
	  HorizontalTextAlignment="Center"
	  VerticalTextAlignment="Center"
	  FontSize="14.5"
	  HeightRequest="30"
	  CurvedBackgroundColor="#0040ff"
	  TextColor="White"
	  CurvedCornerRadius="15">
	</local:CurvedCornersLabel>

</StackLayout>  

 

Don’t be shy and use our awesome CurvedCornersLabel control we just created! 😀

Hit F5 and Run this thing man!

screen-shot-2017-02-19-at-12-17-13-pm  nexus-5-lollipop-screenshot-2

BEHOLD THE FANCINESS!

😀

Cheers everyone, enjoy!

PS: For them lazy ones, you may grab my github commit from here: Xamarin-Playground/XFCurvedCornersLabelControl

Awesome Xamarin Forms Label with HTML Text Formatting…

Why would you wanna use a WebView when you could use your Label to display HTML mark up text in your Xamarin Forms app? 😉

How it all started?

Well some times back I had to implement a Xamarin Forms Label which can display HTML formatted text…

The problem with Xamarin Forms Label?

Well of course you would tell me to use the FormattedText property built into Xamarin Forms Label. But before you say that do you even know how limited that property is? and you have to break up your string in to pieces and rebuild it with Span blocks, and also there’s only a few text formatting options available. Usually HTML has a ton of text formatting options, which you can even get close to with the default Xamarin Forms Span block customization.

So the default Xamarin Forms Label can not do any help at this case.

Solution?

Well we all know it’s super easy to parse HTML text to be rendererd in a Label with Android and iOS native implementation. That’s why I had to drill down to native level and come up with a Custom Label that could display HTML markup text. 😀

Without further due, let’s jump into it! 😉

Create the Custom Control…

So as usual let’s create our Custom Label by subclassing Xamarin Forms Label control.

namespace WhateverYourNamespace
{
    public class HtmlFormattedLabel : Label
    {

    }
}

 

Nothing fancy there… Next are the big stuff!

Xamarin Android implementation…

So here’s the renderer for our HtmlFormattedLabel

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;
            
            Control.SetText(Html.FromHtml(view.Text.ToString()),TextView.BufferType.Spannable);
        }
    }
}

 

So what we basically do here is native Android TextView through the Control property of our renderer and access the SetText() method, and  directly use the Android HTML parser to set your HTML Text.

Xamarin iOS implementation…

Next is our iOS renderer for the custom control.

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            
            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;

            var attr = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();
            attr.DocumentType = NSDocumentType.HTML;
            
            Control.AttributedText = new NSAttributedString(view.Text, attr, ref nsError);
        }
    }
}

 

So here what we do is, we access the native iOS UILabel through the Control property and directly set the AttributedText property with our natively parsed HTML string. 😉

Now unlike Android, I wasn’t much familiar with iOS implementation of HTML text parsing, therefore I took some help from this thread for the above implementation How to display html formatted text in a UILabel ?.

KABOOM! EASY!

Let’s consume this Awesome Label! 😉

Alright time to use the Awesome Label we just created in Xamarin Forms!

Content = new StackLayout
{
	VerticalOptions = LayoutOptions.Center,
	Padding = new Thickness(20,0,20,0),
	Spacing = 30,
	Children = {
		new Label {
			HorizontalTextAlignment = TextAlignment.Center,
			TextColor = Color.Black,
			Text = "Welcome to the awesome HTML Formatter Label" +
			"Control by ÇøŋfuzëÐ SøurcëÇødë!"
		},
		new HtmlFormattedLabel()
		{
			FontSize = 14,
			TextColor = Color.Black,
			Text = 
			   "<html><body><Center>" +
			   "<font size='6'>" +
			   "This is a html formatted text," +
			   "so this is <b>bold text</b>... " +
			   "and this is <u>underline text</u>... " +
			   "and this is <strike>strike through text</strike>... " +
			   "and finally this is <i>italic text</i>... " +
			   "<br />" +
			   "Ops this is html line break..." +
			   "<br />" +
			   "And this is <sup>superscripted</sup> html text."+
			   "</font>" +
			   "<Center></body></html>",
		}
	}
}

 

So here I’m using our HtmlFormattedLabel control and directly setting a HTML formatted text to its Text property. 😀

Now hit F5 and Run that beautiful code! 😉

screen-shot-2017-02-05-at-4-08-31-pmnexus-5-lollipop-screenshot-3

There you have it fellas! 😀

Now you may grab this code from my github: Xamarin-Playground/XFHtmlFormattedLabelControl

Enjoy!

And pass on to another Developer by sharing it! 😉