Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP: Create shadow in XAML [duplicate]

I am currently trying to create a circular button with two ellipse-elements in UWP and want one of them to throw a shadow at a certain angle. I found a way to do so in WPF which looks like this:

WPF XAML:

<Ellipse>
  <Ellipse.BitmapEffect>
    <DropShadowBitmapEffect Color="Black" Direction="-50" ShadowDepth="50" Softness=".7"/>
  </Ellipse.BitmapEffect>
</Ellipse>

What's the equivalent in UWP?

like image 398
Nigel-Lee Avatar asked Dec 13 '22 21:12

Nigel-Lee


2 Answers

The easiest way is to use the DropShadowPanel from UWP Community Toolkit.

So first just install

Install-Package Microsoft.Toolkit.Uwp.UI.Controls -Version 2.0.0

Then use the following code in your XAML

<controls:DropShadowPanel Color="Black"
                          OffsetX="-50"
                          OffsetY="-50"
                          BlurRadius="50"
                          ShadowOpacity=".7"
                          Width="120"
                          Height="120"
                          HorizontalContentAlignment="Stretch"
                          VerticalContentAlignment="Stretch">
    <Ellipse />
</controls:DropShadowPanel>
like image 174
Justin XL Avatar answered Dec 16 '22 09:12

Justin XL


In UWP there is a different component to do this job. It's called the Composition API and is available in the NuGet Package "Win2D.uwp".

Basically you'll need to get the compositor for your visual object with

_compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

and create a drop shadow using the compositor.

_compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;

// create a red sprite visual
var myVisual = _compositor.CreateSpriteVisual();
myVisual.Brush = _compositor.CreateColorBrush(Colors.Red);
myVisual.Size = new System.Numerics.Vector2(100, 100);

// create a blue drop shadow
var shadow = _compositor.CreateDropShadow();
shadow.Offset = new System.Numerics.Vector3(30, 30, 0);
shadow.Color = Colors.Blue;
myVisual.Shadow = shadow;

// render on page
ElementCompositionPreview.SetElementChildVisual(this, myVisual);

The downside beeing, that this is not quite straight forward. You can use different brushes to display images, solid colors or other stuff, it won't apply to existing visuals on screen (as far as I understand it). You can read more about the basics here. Probalby you'll need to use a surface brush, which can hold a wide variety of different visual types, like images. Currently it does not look like there is a ready made component for ellipses though.

Alternatively there exists a xaml extension which will do all that stuff for you using pure xaml, might be worth a shot and maybe also support ellipses.

As an ending note, all of this is currently a work in progress on microsofts part and should become a native part of the UWP API in the future.

like image 21
CShark Avatar answered Dec 16 '22 10:12

CShark