您可以自定义ButtomRender 在 Xamarin Forms 中实现渐变边框。在 OnElementChanged 覆盖方法中编辑 BorderColor 属性。您可以将LinearGradientBrush 传递给Control.BorderBrush 以在UWP 中实现此功能。详情请参考以下代码。
UWP
public class MyButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Element.IsSet(Button.BorderColorProperty) && Element.BorderColor != (Color)Button.BorderColorProperty.DefaultValue)
{
UpdateBorderColor();
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Button.BorderColorProperty.PropertyName)
{
UpdateBorderColor();
}
}
void UpdateBorderColor()
{
Control.BorderBrush = Element.BorderColor != Color.Default ? Element.BorderColor.ToGradientBrush() : (Brush)Windows.UI.Xaml.Application.Current.Resources["ButtonBorderThemeBrush"];
}
}
internal static class ConvertExtensions
{
public static Brush ToGradientBrush(this Color color)
{
var GradientBrush = new LinearGradientBrush();
GradientBrush.StartPoint = new Windows.Foundation.Point(0.5, 0);
GradientBrush.EndPoint = new Windows.Foundation.Point(0.5, 1);
GradientBrush.GradientStops.Add(new GradientStop() { Color = Windows.UI.Colors.LightGray, Offset = 0.0 });
GradientBrush.GradientStops.Add(new GradientStop() { Color = color.ToWindowsColor(), Offset = 1.0 });
return GradientBrush;
}
public static Windows.UI.Color ToWindowsColor(this Color color)
{
return Windows.UI.Color.FromArgb((byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
}
}
IOS
public class MyButtonRenderer : ButtonRenderer
{
CAGradientLayer gradient;
CAShapeLayer shape;
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
gradient = new CAGradientLayer();
// add start color
gradient.Colors = new CGColor[] { ((GradientButton)Element).StartColor.ToCGColor(), Element.BorderColor.ToCGColor() };
shape = new CAShapeLayer();
shape.LineWidth = (nfloat)(Element.BorderWidth);
shape.StrokeColor = UIColor.Black.CGColor;
shape.FillColor = UIColor.Clear.CGColor;
gradient.Mask = shape;
Control.Layer.AddSublayer(gradient);
Control.Layer.BorderColor = UIColor.Clear.CGColor;
}
public override void Draw(CGRect rect)
{
base.Draw(rect);
shape.Path = UIBezierPath.FromRect(rect).CGPath;
gradient.Frame = rect;
}
}
这是code sample,包含UWP和IOS平台请查收。