Sunday, October 10, 2010

WPF - UIElement's Opacity Mask

In this post, we will be discussing how we can apply opacity mask to WPF UIElement. First of, we need to discuss what is opacity mask. When we apply a brush as opacity mask to a UIElement, only alpha channel of the brush is used. All other channels of the brush are ignored. Using Opacity mask we can make portions of an element either transparent or semi transparent.

Using SolidColorBrush for Opacity of whole UIElement:

By using SolidColorBrush for opacity mask, we can control the opacity of whole UIElement. In the example below, we are specifying a SolidColorBrush for opacity mask of a Button.

<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Rectangle Fill="Gray" />
<Button Height="38" Margin="20,48,11,0" Name="button1" VerticalAlignment="Top" Content="Button">
<Button.OpacityMask>
<SolidColorBrush Color="#B2021233" />
</Button.OpacityMask>
</Button>
</Grid>
</Window>

When we run this, it shows as follows:



You can see that opacity mask has ignored the color of the brush. It only has used its alpha channel. If we change the alpha channel to FF, this would be completely opaque, if we change it to 00, it would completely transparent. In the brush used above the alpha channel is specified as:


Using LinearGradientBrush for Transparency of Partial UIElement:
Using LinearGradientBrush allows us to define the transparency at different offsets. Lets define a LinearGradientBrush with three gradient stops with different alpha channels.

<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Rectangle Fill="Gray" />
<Button Height="38" Margin="20,48,11,0" Name="button1" VerticalAlignment="Top" Content="Button">
<Button.OpacityMask>
<LinearGradientBrush >
<GradientStop Color="#80021233" Offset="0"/>
<GradientStop Color="#FF021233" Offset="0.6" />
<GradientStop Color="Transparent" Offset="1"/>
</LinearGradientBrush>
</Button.OpacityMask>
</Button>
</Grid>
</Window>

When we run this, it appears as follows:



Note:
ImageBrush might also be used as OpacityMask. For ImageBrush, we must be using images which support multiple level of transparencies like PNG. Only that portion of the UIElement will be opaque which have visible alpha channel in the ImageBrush used as OpacityMask.