创建具有渐变颜色和弯曲边缘的 Xamarin 按钮 [英] Creating Xamarin button with gradient colour and curved edges

查看:33
本文介绍了创建具有渐变颜色和弯曲边缘的 Xamarin 按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有弯曲边缘(边界半径)的 xamarin Android 按钮.在那里我想将颜色设为渐变.

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

如果我尝试通过绘制画布(作为自定义渲染器)来制作它,它将通过覆盖 ButtonRenderer 的 DispatchDraw 函数来消失曲线边缘,如下所示.

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?

推荐答案

我觉得 XML 更容易理解,所以我会这样做:

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>

在您的按钮 xml 中像这样使用它:

Use it like this in your button xml :

android:background="@drawable/Gradient"

或者像这样的 C# 代码:

Or in C# code like this:

 _button.SetBackgroundResource(Resource.Drawable.Gradient);

这篇关于创建具有渐变颜色和弯曲边缘的 Xamarin 按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆