Tag Archives: Label Radius

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(CurvedBackgroundColor),
		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

Advertisements