[英]UWP. How To Implement drop shadow in code without using DropShadowPanel in
我不是使用 Windows 組合 API 的專家。 如何在不使用DropShadowPanel
情況下在 UWP 中的控件或布局或任何視覺控件上實現 DropShadow 以實現某些目的。 一個附加的例子會很棒。 另外請確保陰影效果在控件后面而不是覆蓋它
在您的代碼中,您已經從控件的合成器創建了一個SpriteVisual
並配置了SpriteVisual
的陰影,但是您沒有將此名為shadowVisual
SpriteVisual
設置為 Visual 樹的子項,因此您看不到要應用的陰影。 您可以將以下代碼放在代碼塊的末尾。
...
ElementCompositionPreview.SetElementChildVisual(Control, shadowVisual);
您的代碼將如下所示:
//Control is the control the shadow is applied to. e.g. Button, TextBlock etc.
Compositor compositor = ElementCompositionPreview.GetElementVisual(Control).Compositor;
var shadowVisual = compositor.CreateSpriteVisual();
var dropShadow = compositor.CreateDropShadow();
shadowVisual.Shadow = dropShadow;
//UpdateShadowSize
Vector2 newSize = new Vector2(0, 0);
if (Control is FrameworkElement contentFE)
{
newSize = new Vector2((float)contentFE.ActualWidth, (float)contentFE.ActualHeight);
//newSize = new Vector2(200, 60);
}
shadowVisual.Size = newSize;
//Some hardcoded values for now
dropShadow.BlurRadius = 8;
dropShadow.Opacity = 0.3f;
dropShadow.Offset = new Vector3(new Vector2(2, 2), 0);
dropShadow.Color = Windows.UI.Colors.Black;
// Sets a Visual as child of the Control’s visual tree.
ElementCompositionPreview.SetElementChildVisual(Control, shadowVisual);
注意:我將dropShadow.Opacity
更改為0.3f
以使陰影更清晰。
- -更新 - -
是的,您可以在 MainContent 后面放置一個特殊元素,然后從該元素創建陰影以在 Main 內容后面創建陰影。 GetAlphaMask
方法應該可以,這里有一個例子,你可以試試。
xml:
<Grid Loaded="Grid_Loaded">
<!-- Canvas to create shadow-->
<Canvas Name="canvas"/>
<TextBlock x:Name="textBlcok" Text="this is text blcok for test shadow"/>
</Grid>
后面的代碼:
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
//The canvas is the element to create shadow
var compositor = ElementCompositionPreview.GetElementVisual(canvas).Compositor;
var dropShadow = compositor.CreateDropShadow();
dropShadow.Color = Colors.Green;
dropShadow.BlurRadius = 8;
dropShadow.Opacity = 20.0f;
dropShadow.Offset = new Vector3(2.5F, 2.5F, 0);
//The textBlock is the main content
var mask = textBlcok.GetAlphaMask();
dropShadow.Mask = mask;
var spriteVisual = compositor.CreateSpriteVisual();
spriteVisual.Size = new Vector2((float)canvas.ActualWidth, (float)canvas.ActualHeight);
spriteVisual.Shadow = dropShadow;
ElementCompositionPreview.SetElementChildVisual(canvas, spriteVisual);
}
https://www.microsoft.com/en-us/p/windows-community-toolkit-sample-app/9nblggh4tlcq
這個應用程序包含許多控件來構建一個漂亮的 uwp 應用程序,它有一個陰影庫,你可以看到如何在你的項目中實現它,並給你任何控件的陰影
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.