我有一个带有弯曲边缘(边框半径(的Xamarin Android按钮。我想在那里制作颜色作为渐变。
如果我尝试通过绘画画布(作为自定义渲染器(来实现它,它将消失,弯曲边缘,如下所示,通过覆盖纽扣的dispatchdraw函数。
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);
}
使用上述代码,IT按钮将消失弯曲的边缘。在此代码之前,我将使用背景属性设置颜色。使用该属性,我可以看到弯曲的边缘,但没有上述代码。
所以我的假设是,如果我可以为按钮的背景颜色属性设置梯度颜色,这将起作用,不幸的是,我找不到方法。
有人可以帮助我实现这一目标吗?
我发现XML更易于理解,所以我会做这样的事情:
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中使用这样的使用:
android:background="@drawable/Gradient"
或这样的C#代码:
_button.SetBackgroundResource(Resource.Drawable.Gradient);