【发布时间】:2018-06-23 10:11:00
【问题描述】:
我正在尝试在 android 中实现一个带阴影的按钮。正如您在image 中看到的那样,我有 3 种类型的按钮。
左侧是默认按钮,使用此按钮:<Button FontSize="14" Text="Button" /> 阴影已定义并在按下时正确动画。
中间是这样的:<Button FontSize="14" Text="Button" BackgroundColor="Red" TextColor="White" />改变背景颜色使按钮更高,并去除阴影。
正确的是我使用了自定义渲染器,我使用了自定义ViewOutlineProvider 并将其分配给Control 的View.OutlineProvider 属性。标记是这样的:<ctrl:MaterialButton FontSize="14" Text="Discard Changes" BackgroundColor="#6200EE" HeightRequest="36" TextColor="White" />
这是自定义渲染器类:
[assembly: ExportRenderer(typeof(MaterialButton), typeof(MaterialButtonRenderer))]
namespace XF.Material.Droid.Renderers
{
public class MaterialButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer
{
private MaterialButton _materialButton;
public MaterialButtonRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (e?.NewElement != null)
{
_materialButton = this.Element as MaterialButton;
this.Control.Text = this.Control.Text.ToUpper();
this.Control.OutlineProvider = new MaterialButtonOutlineProvider(_materialButton.CornerRadius);
}
}
private class MaterialButtonOutlineProvider : ViewOutlineProvider
{
private readonly int _cornerRadius;
public MaterialButtonOutlineProvider(int cornerRadius)
{
_cornerRadius = cornerRadius;
}
public override void GetOutline(Android.Views.View view, Outline outline)
{
var cornerRadius = MaterialExtensions.ConvertDpToPx(_cornerRadius);
outline.SetRoundRect(0, 0, view.Width, view.Height, cornerRadius);
}
}
}
}
我还尝试在渲染器中设置View.Elevation 和View.TranslationZ 属性,但仍然没有阴影。如果您仔细观察右侧按钮的角,您可以看到一个轮廓,但它似乎已被剪掉。
【问题讨论】:
标签: android xamarin xamarin.forms xamarin.android