为元素创建投影的代码:
var compositor = ElementCompositionPreview.GetElementVisual(this.btn).Compositor;
var spriteVisual = compositor.CreateSpriteVisual();
spriteVisual.Size = new Vector2((float)btn.ActualWidth, (float)btn.ActualHeight);
var dropShadow = compositor.CreateDropShadow();
dropShadow.Offset = new Vector3(10, 10, 0);
dropShadow.Color = Colors.Orange;
spriteVisual.Shadow = dropShadow;
ElementCompositionPreview.SetElementChildVisual(this.btn, spriteVisual);
但阴影重叠按钮。如何使阴影不重叠按钮?
答案 0 :(得分:4)
您有两个选择:
您可以为 spriteVisual
创建画笔 var compositor = ElementCompositionPreview.GetElementVisual(Button).Compositor;
var spriteVisual = compositor.CreateSpriteVisual();
spriteVisual.Size = new Vector2((float)Button.ActualWidth, (float)Button.ActualHeight);
var dropShadow = compositor.CreateDropShadow();
dropShadow.Offset = new Vector3(10, 10, 0);
dropShadow.Color = Colors.Orange;
var colorBrush = compositor.CreateColorBrush(Colors.Green);
spriteVisual.Shadow = dropShadow;
spriteVisual.Brush = colorBrush;
ElementCompositionPreview.SetElementChildVisual(Button, spriteVisual);
或者在按钮和 SetElementChildVisual 之前为您的spriteVisual创建XAML容器到阴影画布
<Grid>
<Canvas x:Name="Shadow"/>
<Button x:Name="Button" Width="300" Height="100" Background="Green" HorizontalAlignment="Center"/>
</Grid>