
Everybody knows those lottery games where you have to scratch a card to reveal some symbols that tell you if you’ve won money. Here’s an easy way to achieve the same effect in WPF, using xaml only.
Wpf has a control that let’s the user draw on it’s surface, the InkCanvas. By placing this exactly behind an image it's invisble to the user, but can be used. To make sure all mouse-clicks will come thru to the InkCanvas, the IsHitTestVisible property on the Image has to be set to false. Now, by adding a VisualBrush to the OpacityMask of the image, everything drawn on the InkCanvas is used as OpacityMask.
By default, the background of the InkCanvas is set to white. This will cause the OpacityMask to be filled, and thus the image is shown. To prevent this from happening, the background color of the InkCanvas is set to transparent or {x:Null}. The size of the brush used by the InkCanvas is increased a bit. This will make it a little quicker to ‘scratch’.
A Border is used to add the look-and-feel of a scratchcard, by setting it’s background to gray.
Here’s a simplefied version of the xaml used in the example.
<Border Background="#FF909090" BorderBrush="#FF000000"
BorderThickness="2,2,2,2">
<Grid Width="Auto" Height="Auto" Background="{x:Null}">
<InkCanvas x:Name="inkCanvas"
Background="{x:Null}">
<InkCanvas.DefaultDrawingAttributes>
<DrawingAttributes Height="25" Width="25"/>
</InkCanvas.DefaultDrawingAttributes>
</InkCanvas>
<Image IsHitTestVisible="False"
Source="DSC00058.JPG" Stretch="Fill">
<Image.OpacityMask>
<VisualBrush
Visual="{Binding ElementName=inkCanvas}"/>
</Image.OpacityMask>
</Image>
</Grid>
</Border>
Monday, March 02, 2009 3:42 PM