I am trying to achieve a button with shadow in android. As you can see in this image I have 3 types of buttons.
The left one is the default button using this: <Button FontSize="14" Text="Button" />
The shadow is defined and properly animates when pressed.
The middle one is this: <Button FontSize="14" Text="Button" BackgroundColor="Red" TextColor="White" />
Changing the background color makes the button more taller and removes the shadow.
The right one I used a custom renderer, and I used a custom ViewOutlineProvider
and assign it to the Control's View.OutlineProvider
property. The markup is this: <ctrl:MaterialButton FontSize="14" Text="Discard Changes" BackgroundColor="#6200EE" HeightRequest="36" TextColor="White" />
This is the custom renderer class:
[assembly: ExportRenderer(typeof(MaterialButton), typeof(MaterialButtonRenderer))]
namespace XF.Material.Droid.Renderers
{
public class MaterialButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer
{
private MaterialButton _materialButton;
public MaterialButtonRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (e?.NewElement != null)
{
_materialButton = this.Element as MaterialButton;
this.Control.Text = this.Control.Text.ToUpper();
this.Control.OutlineProvider = new MaterialButtonOutlineProvider(_materialButton.CornerRadius);
}
}
private class MaterialButtonOutlineProvider : ViewOutlineProvider
{
private readonly int _cornerRadius;
public MaterialButtonOutlineProvider(int cornerRadius)
{
_cornerRadius = cornerRadius;
}
public override void GetOutline(Android.Views.View view, Outline outline)
{
var cornerRadius = MaterialExtensions.ConvertDpToPx(_cornerRadius);
outline.SetRoundRect(0, 0, view.Width, view.Height, cornerRadius);
}
}
}
}
I also tried to set the View.Elevation
and View.TranslationZ
property in the renderer, but still no shadow. If you look closely the corners of the right button, you can see an outline but it appears to have been cut.