Search code examples
iosxamarinxamarin.formsuigraphicscontext

Custom Rendering on IOS a CardView from Frame


I am trying to make a CardView on IOS Xamarin Forms by subclassing the Frame and making a custom renderer. I want to achieve something like this:

enter image description here

Upon looking into the API on setting a shadow, I've done this:

[assembly: ExportRenderer(typeof(CardView), typeof(CardViewRenderer))]
namespace TrabbleMobile.iOS.CustomRenderers
{
    public class CardViewRenderer : FrameRenderer
    {
        public override void Draw(CGRect rect)
        {
            var cardView = (CardView)this.Element;

            using (var context = UIGraphics.GetCurrentContext())
            {
                //nfloat cornerRadius = 2;
                float shadowOffsetWidth = 2;
                float shadowOffsetHeight = 4;
                var shadowColor = new CGColor(0, 0, 0, (nfloat)0.5);
                var boxColor = new CGColor(255, 255, 255);
                var shadowBlur = (float)0.5;
                var offset = new CGSize(shadowOffsetWidth, shadowOffsetHeight);

                context.SetShadow(offset, shadowBlur, shadowColor);

However, it does not render as it should and no shadow at all.


Solution

  • I've done this, and the way that I did this is thru custom rendering on IOS and here is the custom renderer code:

        public class CardViewRenderer : FrameRenderer
        {
    
            public override void Draw(CGRect rect)
            {
                SetupShadowLayer();
                base.Draw(rect);
            }
    
            void SetupShadowLayer()
            {
                Layer.CornerRadius = 2; // 5 Default
                if (Element.BackgroundColor == Xamarin.Forms.Color.Default)
                {
                    Layer.BackgroundColor = UIColor.White.CGColor;
                }
                else
                {
                    Layer.BackgroundColor = Element.BackgroundColor.ToCGColor();
                }
    
                Layer.ShadowRadius = 2; // 5 Default
                Layer.ShadowColor = UIColor.Black.CGColor;
                Layer.ShadowOpacity = 0.4f; // 0.8f Default
                Layer.ShadowOffset = new CGSize(0f, 2.5f);
    
                if (Element.OutlineColor == Xamarin.Forms.Color.Default)
                {
                    Layer.BorderColor = UIColor.Clear.CGColor;
                }
                else
                {
                    Layer.BorderColor = Element.OutlineColor.ToCGColor();
                    Layer.BorderWidth = 1;
                }
    
                Layer.RasterizationScale = UIScreen.MainScreen.Scale;
                Layer.ShouldRasterize = true;
            }
        }