Pixiview/Gallery.Android/Renderers/CardViewRenderer.cs
2021-08-04 10:27:41 +08:00

85 lines
2.9 KiB
C#

using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using Android.Views;
using Gallery.Droid.Renderers;
using Gallery.UI;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CardView), typeof(CardViewRenderer))]
namespace Gallery.Droid.Renderers
{
public class CardViewRenderer : VisualElementRenderer<CardView>
{
public CardViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CardView> e)
{
base.OnElementChanged(e);
var element = e.NewElement;
if (element != null)
{
var radius = element.CornerRadius;
if (radius > 0)
{
var density = Resources.DisplayMetrics.Density;
OutlineProvider = new CornerRadiusOutlineProvider(element, radius, density);
ClipToOutline = true;
//var drawable = new RoundCornerDrawable(radius * density);
//drawable.SetColorFilter(element.BackgroundColor.ToAndroid(), PorterDuff.Mode.Src);
//((Android.Views.View)this).SetBackground(drawable);
Elevation = (float)(element.ShadowOffset.Height + 2) * density;
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var element = Element;
if (element == null)
{
return;
}
switch (e.PropertyName)
{
case nameof(CardView.ShadowOffset):
var density = Resources.DisplayMetrics.Density;
Elevation = (float)(element.ShadowOffset.Height + 2) * density;
break;
}
}
class CornerRadiusOutlineProvider : ViewOutlineProvider
{
readonly Element element;
readonly float radius;
readonly float density;
public CornerRadiusOutlineProvider(Element formsElement, float radius, float density)
{
element = formsElement;
this.radius = radius * density;
this.density = density;
}
public override void GetOutline(Android.Views.View view, Outline outline)
{
float scale = density;
double width = (double)element.GetValue(VisualElement.WidthProperty) * scale;
double height = (double)element.GetValue(VisualElement.HeightProperty) * scale;
var rect = new Android.Graphics.Rect(0, 0, (int)width, (int)height);
outline.SetRoundRect(rect, radius);
}
}
}
}