我需要按钮上的渐变背景。我使用Custome Renderer来做到这一点。这是我的代码:
[assembly: ExportRenderer (typeof (Xamarin.Forms.Button), typeof (EvoMotorOilApp.Droid.MyButtonRender))]
...
protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)
{
base.DispatchDraw(canvas);
var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,
Color.FromRgba(255, 255, 255, 255).ToAndroid(),
Color.FromRgba(70, 70, 70, 50).ToAndroid(),
Android.Graphics.Shader.TileMode.Repeat);
var paint = new Android.Graphics.Paint() {
Dither = true,
};
paint.SetShader(gradient);
canvas.DrawPaint(paint);
}
但结果渐变层延伸到按钮之外,并且他具有锐角。怎么做会形成渐变就像按钮形式一样? 有截图:https://drive.google.com/file/d/0B8C-lgUpGFGDVzhVUzJrMm01cFU/view?usp=sharing
答案 0 :(得分:0)
只需将控件背景颜色设置为GradientDrawable
:
public class GradientButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var gradient = new GradientDrawable(GradientDrawable.Orientation.TopBottom, new[] {
Color.FromRgba(255, 255, 255, 255).ToAndroid().ToArgb(),
Color.FromRgba(70, 70, 70, 50).ToAndroid().ToArgb()
});
Control.SetBackgroundDrawable(gradient);
}
}
}
您还可以使用StateListDrawable
为正常/按下/禁用按钮状态设置不同的颜色。