Forum Xamarin.Android

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to drop color shadow to a button

I want to add shadow to a button in Xamarin on Android as well as iOS.
I want to produce design:
I have tried customizing button on Xamarin.Android with following code:

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);

    Control.SetShadowLayer(10, 10, 10, Android.Graphics.Color.Rgb((int)e.NewElement.BackgroundColor.R,
                                                                (int)e.NewElement.BackgroundColor.G,
                                                                (int)e.NewElement.BackgroundColor.B));
    this.Elevation = 50;
}

But it does not produce color shadow around the border. I have also tried to use framerenderer with HasShadow property to work as a Button. But no luck.

Any help?

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Try to use a frame to wrap your button to display a shadow:

    <Frame VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" CornerRadius="10" Padding="0" BackgroundColor="LightBlue" HasShadow="True">
        <Button Text="Confirm" BackgroundColor="Transparent" Clicked="Button_Clicked"/>
    </Frame>
    

    We still need a custom renderer to manipulate the shadow on Android like:

    [assembly: ExportRenderer(typeof(Frame), typeof(CustomFrameRenderer))]
    namespace Sample.Droid
    {
        public class CustomFrameRenderer : Xamarin.Forms.Platform.Android.AppCompat.FrameRenderer
        {
            public CustomFrameRenderer(Context context) : base(context)
            {
            }
    
            protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
            {
                base.OnElementChanged(e);
    
                if (e.NewElement.HasShadow)
                {
                    SetOutlineSpotShadowColor(Android.Graphics.Color.Red);
                    Elevation = 30.0f;
                    TranslationZ = 0.0f;
                    SetZ(30f);
                }
            }
        }
    }
    

    Create a custom frame in your Forms so that we could dynamically change the color instead of the red here.
    Here is the effect:

Sign In or Register to comment.