Monday, February 5, 2018

How to set shadow effect on ImageView

Leave a Comment

I'm tryin' to set shadow on an Image view on Xamarin.Forms (targeting the Android platform) and I got some examples on the internet.

The PCL code is quite simple, and the platform seemed pretty easy too. The recipe available at the official xamarin developer site is something like this:

[assembly: ResolutionGroupName("MyGroupName")] [assembly: ExportEffect(typeof(LabelShadowEffect), "ShadowEffect")] namespace MyWorkspace {     public class LabelShadowEffect : PlatformEffect     {         protected override void OnAttached()         {             try             {                 var control = (Control as TextView); // TextView have the SetShadowLayer method, but others views don't                  var effect = (ShadowEffect)Element.Effects.FirstOrDefault(e => e is ShadowEffect);                 if (effect != null)                 {                     float radius = effect.Radius;                     float distanceX = effect.DistanceX;                     float distanceY = effect.DistanceY;                     Android.Graphics.Color color = effect.Color.ToAndroid();                     control?.SetShadowLayer(radius, distanceX, distanceY, color);                 }             }             catch (Exception)             {                            }         }          protected override void OnDetached()          {          }     } } 

So I've noticed that this recipe works only for components that render with TextView (that's the only class with the SetShadowLayer method). In other sources I saw something more generic like:

public class ShadowEffect : PlatformEffect {     protected override void OnAttached ()     {         Container.Layer.ShadowOpacity = 1;         Container.Layer.ShadowColor = UIColor.Black.ToCGColor;         Container.Layer.ShadowRadius = 6;     }      protected override void OnDetached ()     {         Container.Layer.ShadowOpacity = 0;     } } 

By the use of UIColor I get that it's targeting iOS platform. No such a thing like this on Android views. I took a look at the XF FrameRenderer source code but I was not able to understand how they made the shadow effect works.

Someone can help me with this?

2 Answers

Answers 1

Please try this below code will work

<Frame OutlineColor="Transparent" Padding="0" CornerRadius="0" VerticalOptions="Center" BackgroundColor="Teal">     <Image Source="Imagename" Aspect="Fill" /> </Frame> 

Answers 2

I recommend using the Elevation property instead of ShadowLayer; Android will add the correct shadow itself based on the elevation you give, and it will adhere to Material Design.

Though you will have to use a custom renderer for this approach, and will need to create a different renderer for iOS/UWP.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment