2015-09-08 51 views
0

我需要按鈕上的漸變背景。我用Custome Renderer來做到這一點。在這裏我的代碼:漸變層形式作爲Xamarin.Forms中按鈕的形式Android

[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); 


    } 

但是結果是梯度層延伸到按鈕和HES有銳角。如何做到這一點將形成漸變像按鈕形式? 有一個截圖:https://drive.google.com/file/d/0B8C-lgUpGFGDVzhVUzJrMm01cFU/view?usp=sharing

回答

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爲正常/按下/關閉按鈕狀態設置不同的顏色。