0
votes

I'm looking for a way to create a custom renderer for a button in xamarin forms, so that I can get rounded corners on the left side of the button. I have tried searching for a solution, but without any luck.

4
Go easy on the down votes, there are no tutorials or anything about this topic of a button rounded on one side only. - Jesper Højer

4 Answers

1
votes

There is a very popular open source project FlexButton which can help solving the challenge you are facing. If for some reason you would still like to solve it yourself, without introducing external dependencies, then you can check the source code of this project to get a better idea on how it can be achieved.

Alternative option is to search the web more precisely and check threads like this.

Good luck.

1
votes

On Android you can use shape in your drawable folder, named layout_bg:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="3dp" android:color="#B1BCBE" />
    <corners
        android:topLeftRadius="10dp"
        android:bottomLeftRadius="10dp"/>
</shape>

In your custom render:

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
    base.OnElementChanged(e);
    if (Control != null) {
        Control.SetBackgroundResource(Resource.Drawable.layout_bg);
    }
}

Result:

enter image description here

1
votes

For making different corner radius for button or any control.You need declare top left, top right ,bottom left bottom right corner radius in float[] array varaible and pass the float variable in SetCornerRadii() Method of GradientDrawable.

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

  base.OnElementChanged(e);

        if (Control != null)
        {
            Control.SetAllCaps(false);
            GradientDrawable gradientDrawable = new GradientDrawable();                
            float[] radius= new float[8];
            radius[0] = 46f;   //Top Left corner
            radius[1] = 46f;   //Top Left corner
            radius[2] = 0;     //Top Right corner
            radius[3] = 0;     //Top Right corner
            radius[4] = 0;     //Bottom Right corner
            radius[5] = 0;     //Bottom Right corner
            radius[6] = 46f;   //Bottom Left corner
            radius[7] = 46f;   //Bottom Left corner
            gradientDrawable.SetCornerRadii(radius);
            Control.SetBackground(gradientDrawable);
        }
    }

enter image description here

0
votes
Color background = Color.ParseColor("#ff3c4550");
GradientDrawable shape = new GradientDrawable();
shape.SetCornerRadius(10);
shape.SetColor(background.ToArgb());
Background = shape;