Drop shadow is above the text

白昼怎懂夜的黑 提交于 2019-12-08 02:56:26

问题


I'm adding a drop shadow to a Xamarin.UWP project (but the question is not really Xamarin-specific but UWP in general):

bool IsShadowSupported => ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 3); // SDK >= 14393

if (IsShadowSupported) {
  var compositor = ElementCompositionPreview.GetElementVisual(Control).Compositor;
  dropShadow = compositor.CreateDropShadow();
  if (Control is Windows.UI.Xaml.Controls.TextBlock textBlock)
    dropShadow.Mask = textBlock.GetAlphaMask();
  shadowVisual = compositor.CreateSpriteVisual();
  shadowVisual.Shadow = dropShadow;
  ElementCompositionPreview.SetElementChildVisual(Control, shadowVisual);
  ...
  dropShadow.Offset = new Vector3((float)Shadow.GetDistanceX(Element), (float)Shadow.GetDistanceY(Element), -5f);
}

It runs and the shadow appears - but above the text, not beneath it. At first I thought this will be determined by the Z coordinate of the offset but no, no negative, positive or zero value there changes anything. The shadow looks like this:

Which is not a bad effect on its own but it's not what was requested: white text and a dark grey shadow beneath it.


回答1:


The problem is that the SetElementChildVisual sets the visual as the last child of the given element, which will make the shadow appear above the TextBlock. Unfortunately not even the parent of the TextBlock is enough, you should instead have a adjacent element that will host the shadow:

<Grid x:Name="ShadowHost" />
<TextBlock x:Name="Hello" Text="Hello" />

Now use ShadowHost instead of Control in your code except for the GetAlphaMask call where you should use the TextBlock instead.

Of course this is quite some work to make shadows work, which is why you can try to use the Windows Community Toolkit's DropShadowPanel instead - see documentation for more info.



来源:https://stackoverflow.com/questions/51580042/drop-shadow-is-above-the-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!