了解OpacityMask的有效区域

时间:2017-08-22 07:50:59

标签: c# wpf xaml opacitymask

我使用WPF opacitymask来“切断”'动画区域的形状。我注意到默认情况下,opacitymask仅适用于面板的内容而不是整个面板。

将背景设置为透明是一种可行的解决方案(显然它会强制拉伸opacitymask。但感觉就像是一种解决方法,所以我很好奇是否有'意图&# 39;将opacitymask拉伸到整个网格的方法。

请参阅下面的示例代码和结果:

<Window x:Class="Sandbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="800">
<Window.Resources>
    <ImageBrush x:Key="SomeAlphaMaskBrush" ImageSource="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dog_silhouette.svg/1034px-Dog_silhouette.svg.png"></ImageBrush>
</Window.Resources>
<Grid Name="Container">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid Name="Container01" OpacityMask="{StaticResource SomeAlphaMaskBrush}" Background="Transparent">
        <!-- Container01 has a transparent background and it makes the OpacityMask stretch to the entire Container01 -->
        <Rectangle Margin="70" Fill="Black"/>
    </Grid>
    <Grid Grid.Column="1" Name="Container02" OpacityMask="{StaticResource SomeAlphaMaskBrush}">
        <!-- Container02 has no background, the opacitymask is applied only to its content -->
        <Rectangle Margin="70" Fill="Black"/>
    </Grid>
</Grid>

Resulting output hereOutput

1 个答案:

答案 0 :(得分:0)

您可以使用ViewportUnits="Absolute"VisualBrush属性来设置所需的OpacityMask矩形:

<ImageBrush x:Key="SomeAlphaMaskBrush" ViewportUnits="Absolute" Viewport="0 0 20 20" ImageSource="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dog_silhouette.svg/1034px-Dog_silhouette.svg.png"/>