Skip to content

Instantly share code, notes, and snippets.

@standamikes
Created December 6, 2018 09:06
Show Gist options
  • Save standamikes/d5aa1ae44c82c895af567e5f385bfa35 to your computer and use it in GitHub Desktop.
Save standamikes/d5aa1ae44c82c895af567e5f385bfa35 to your computer and use it in GitHub Desktop.
using Xamarin.Forms;
namespace YourProject.Core.Effects
{
public class FrameCornerRadius : RoutingEffect
{
public FrameCornerRadius()
: base("YourProject.FrameCornerRadiusEffect")
{
}
public float CornerRadius { get; set; }
}
}
using Android.Graphics;
using Android.Views;
using System.Linq;
using YourProject.Core.Effects;
using YourProject.Droid.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName(nameof(YourProject))]
[assembly: ExportEffect(typeof(FrameCornerRadiusEffect), nameof(FrameCornerRadiusEffect))]
namespace YourProject.Droid.Effects
{
class FrameCornerRadiusEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (FrameCornerRadius)Element.Effects.FirstOrDefault(e => e is FrameCornerRadius);
if (effect != null)
{
Control.ClipToOutline = true;
Control.OutlineProvider = new RoundedOutlineProvider(effect.CornerRadius);
}
}
catch (System.Exception ex)
{
throw new System.Exception($"Cannot set property on attached control. Error: {ex.Message}");
}
}
protected override void OnDetached()
{
}
private class RoundedOutlineProvider : ViewOutlineProvider
{
private readonly float radius;
public RoundedOutlineProvider(float radius)
{
this.radius = radius;
}
public override void GetOutline(Android.Views.View view, Outline outline)
{
outline?.SetRoundRect(0, 0, view.Width, view.Height, radius);
}
}
}
}
using Foundation;
using System.Diagnostics;
using System.Linq;
using YourProject.Core.Effects;
using YourProject.iOS.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ResolutionGroupName(nameof(YourProject))]
[assembly: ExportEffect(typeof(FrameCornerRadiusEffect), nameof(FrameCornerRadiusEffect))]
namespace YourProject.iOS.Effects
{
[Preserve(AllMembers = true)]
public class FrameCornerRadiusEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
var effect = (FrameCornerRadius)Element.Effects.FirstOrDefault(e => e is FrameCornerRadius);
if (effect != null)
{
Container.Layer.CornerRadius = effect.CornerRadius;
Container.Layer.MasksToBounds = true;
}
}
catch (System.Exception ex)
{
throw new System.Exception($"Cannot set property on attached control. Error: {ex.Message}");
}
}
protected override void OnDetached()
{
}
}
}
@noque-lind
Copy link

Thank you very much for this snippet. I'm looking at implementing rounded view using the outline provider too. I have gotten it to work, although I find that when I rotate on Android the effect is removed. Have you solved that issue, or encountered it yourself?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment