Creating Xamarin button with gradient colour and curved edges

时间秒杀一切 提交于 2019-12-11 09:19:58

问题


I have a xamarin Android button with curved edges (Border radius). There I want to make colour as gradient.

If I try to make it by painting the canvas (as a custom renderer) it will disappear curved edges as follows by overriding the ButtonRenderer's DispatchDraw function.

protected override void DispatchDraw(Canvas canvas)
{
    var gradient = new Android.Graphics.LinearGradient(0, 0, Width, Height,
        this.StartColor.ToAndroid(),
        this.EndColor.ToAndroid(),
        Android.Graphics.Shader.TileMode.Clamp);
    var paint = new Android.Graphics.Paint()
    {
        Dither = true,
    };
    paint.SetShader(gradient);
    canvas.DrawPaint(paint);
    base.DispatchDraw(canvas);
}

With the above code it button will disappear the curved edges. Before this code I was settings the color with the background property. With that property I can see the curved edges but not with the above code.

So my assumption is if I can set the gradient color for the background color property of the button this will work, unfortunately I couldn't find a way to do it.

Could someone help me to achieve this?


回答1:


I find XML to be more understandable so, i would do something like this:

Gradient.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item>
<shape android:shape="rectangle">
    <!--make a gradient background-->
    <gradient
        android:type="linear"
        android:startColor="#556B2F"
        android:endColor="#BDB76B"
        android:centerColor="#ffffff"
        android:angle="90"
        android:gradientRadius="90"
        />
    <!--apply a border around button-->
    <stroke android:color="#006400" android:width="2dp" />
    <!-- make the button corners rounded-->
    <corners android:radius="25dp"/>
</shape>
</item>
</selector>

Use it like this in your button xml :

android:background="@drawable/Gradient"

Or in C# code like this:

 _button.SetBackgroundResource(Resource.Drawable.Gradient);


来源:https://stackoverflow.com/questions/50069116/creating-xamarin-button-with-gradient-colour-and-curved-edges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!