Home > Back-end >  Xamarin iOS Round only some corners of a Button
Xamarin iOS Round only some corners of a Button

Time:11-24

I need to achieve this effect on Xamarin.iOS for a Button (so just the blue button with rounded corners in the image), basically just make any corner of a button rounded, but not all of them at once. I prefer not using another nuget package like "Pancake" which I saw as an answer. Is there any platform specific customization on iOS to match the Android one?

enter image description here

I managed to achieve this on ANDROID like this:

public class DroidCustomButtonRenderer : ButtonRenderer
    {
        public DroidCustomButtonRenderer(Context context) : base(context)
        {
        }

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

            if (Control != null)
            {                
                GradientDrawable gradientDrawable = new GradientDrawable();                         gradientDrawable.SetColor(global::Android.Graphics.Color.ParseColor(AppConstants.Constants.CUSTOM_BACK_BUTTON_COLOR_NEW));

                float[] radius = new float[8];

                radius[0] = 0;   //Top Left corner
                radius[1] = 0;   //Top Left corner
                radius[2] = 46f;     //Top Right corner
                radius[3] = 46f;     //Top Right corner
                radius[4] = 46f;     //Bottom Right corner
                radius[5] = 46f;     //Bottom Right corner
                radius[6] = 0;   //Bottom Left corner
                radius[7] = 0;   //Bottom Left corner

                gradientDrawable.SetCornerRadii(radius);
                Control.SetBackground(gradientDrawable);
            }
        }
    }

How can I achieve same on iOS please?

public class iOSCustomButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            // ?
        }
    }

CodePudding user response:

You can use MaskedCorners in your iOS class to control the display of graphics.

Here is my implementation class for your reference:

[assembly: ExportRenderer(typeof(CustomButton),typeof(CurvedCornersButtonRenderer))]
namespace xxx.iOS
{
    class CurvedCornersButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            Control.BackgroundColor = UIColor.Blue;
            Control.ClipsToBounds = true;
            Control.Layer.CornerRadius = 15;
            Control.Layer.MaskedCorners = CoreAnimation.CACornerMask.MaxXMinYCorner | CoreAnimation.CACornerMask.MaxXMaxYCorner;
        }
   
    }
}
  • Related