I am trying to write a custom renderer in a Forms project for an Entry which features text above the entry.
But my custom entry cuts off the bottom section of the entry. The border actually draws correctly, along with the text, however the bottom portion of the view is cut off. I tested this without the text and the drawable was drawn as expected. I'm sure this has something to do with the bounds, clipBounds or the size of the canvas but I can't for the life of me figure it out -- if anyone can it would be must appreciated!
My way to get this up and running was to use a drawable for the border around the entry with some additional code in the DrawChild method to try and create the text.
Here in OnElementChanged I set the drawable for my Entry along with some other values.
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
//Initialise textview to get textsize
tv = new Android.Widget.TextView(Context);
//Set values for our paint used for our label text
paint.TextSize = tv.TextSize;
//Set fields
entry = (CustomEntry)Element;
label = entry.EntryLabel;
//Set typical values
Control.SetHintTextColor(Xamarin.Forms.Color.FromHex("#B8B8B8").ToAndroid());
backgroundDrawable = Context.GetDrawable(Resource.Drawable.entry_background);
//Set as our current background with left and right padding
Control.Background = backgroundDrawable;
Control.SetPadding(Control.PaddingLeft + 10, Control.PaddingTop, Control.PaddingRight +10, Control.PaddingBottom);
}
}
Then in my DrawChild method I aim to draw the text at (0, paint.TextSize) as the docs states that the y axis in .DrawText() is the baseline of the text. Then I draw the actual entry underneath this baseline by 4 pixels.
protected override bool DrawChild(Canvas canvas, Android.Views.View child, long drawingTime)
{
try
{
//Handle our label drawing
DrawLabel(canvas);
//Set the child element's Y position to be lower than the label and draw it.
child.SetY(paint.TextSize + 4);
return base.DrawChild(canvas, child, drawingTime);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception in CustomEntry: " + e.Message);
}
return base.DrawChild(canvas, child, drawingTime);
}
/// <summary>
/// Draw our label in either the focused or unfocused colours.
/// </summary>
/// <param name="canvas">Canvas</param>
protected void DrawLabel(Canvas canvas)
{
if (HasFocus)
canvas.DrawText(label, 0, label.Length, 0, paint.TextSize, focusPaint);
else
canvas.DrawText(label, 0, label.Length, 0, paint.TextSize, paint);
}