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

61 lines
1.9 KiB
C#

using Android.Content;
using Android.Graphics;
using Gallery.Droid.Renderers;
using Gallery.UI;
using Xamarin.Forms;
[assembly: ExportRenderer(typeof(RoundImage), typeof(RoundImageRenderer))]
namespace Gallery.Droid.Renderers
{
public class RoundImageRenderer : Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer
{
public RoundImageRenderer(Context context) : base(context)
{
}
public override void SetBackgroundColor(Android.Graphics.Color color)
{
// nothing
}
protected override void OnDraw(Canvas canvas)
{
if (Element is RoundImage image)
{
var radius = image.CornerRadius;
var mask = image.CornerMasks;
if (radius > 0 && mask != CornerMask.None)
{
var r = Resources.DisplayMetrics.Density * radius;
var radii = new float[8];
if ((mask & CornerMask.LeftTop) == CornerMask.LeftTop)
{
radii[0] = radii[1] = r;
}
if ((mask & CornerMask.RightTop) == CornerMask.RightTop)
{
radii[2] = radii[3] = r;
}
if ((mask & CornerMask.RightBottom) == CornerMask.RightBottom)
{
radii[4] = radii[5] = r;
}
if ((mask & CornerMask.LeftBottom) == CornerMask.LeftBottom)
{
radii[6] = radii[7] = r;
}
var path = new Path();
int width = Width;
int height = Height;
path.AddRoundRect(new RectF(0, 0, width, height), radii, Path.Direction.Cw);
canvas.ClipPath(path);
}
}
base.OnDraw(canvas);
}
}
}