Create RotatedLabel.cs
in you shared mobile project:
using Xamarin.Forms;
namespace YourProject.Views.Controls
{
public class RotatedLabel : View
{
public static BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(RotatedLabel), null, BindingMode.TwoWay);
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
}
}
Create RotatedLabelRenderer.cs
in your Android project:
using Android.Content;
using Android.Graphics;
using Android.Text;
using YourProject.Views.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(RotatedLabel), typeof(YourProject.Droid.Views.Renderers.RotatedLabelRenderer))]
namespace YourpPoject.Droid.Views.Renderers
{
public class RotatedLabelRenderer : ViewRenderer
{
private readonly Context _context;
public RotatedLabelRenderer(Context c) : base(c)
{
_context = c;
}
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.NewElement is RotatedLabel text)
{
string title = text.Text;
SetNativeControl(new RotatedTextView(_context, title));
}
}
}
public class RotatedTextView : Android.Views.View
{
private readonly int DEFAULT_TEXT_SIZE = 30;
private readonly string _text;
private TextPaint _textPaint;
public RotatedTextView(Context c, string title) : base(c)
{
_text = title;
InitLabelView();
}
private void InitLabelView()
{
_textPaint = new TextPaint
{
AntiAlias = true,
TextAlign = Paint.Align.Center,
TextSize = DEFAULT_TEXT_SIZE,
Color = new Android.Graphics.Color(0, 0, 0),
};
}
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
if (!string.IsNullOrEmpty(_text))
{
float x = (Width / 2) - (DEFAULT_TEXT_SIZE / 3);
float y = (Height / 2);
canvas.Rotate(90);
canvas.DrawText(_text, y, -x, _textPaint);
}
}
}
}