Home Contact

Timmy Kokke

…just sorting my bubbles…

News




Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged

Twitter












Tag Cloud


Archives

Post Categories

Image Galleries

Silverlight

Syndication:

Scratchcard in WPF

image

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>    
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Monday, March 02, 2009 3:42 PM

Feedback

# re: Scratchcard in WPF

That is pretty slick. I'm just really getting started with WPF and the InkCanvas seems really powerful... if quite confusing. I'm just glad to finally get some Tablet PC love built into the mainline technologies!

Thanks for some techniques things to learn! 3/14/2009 12:02 AM | Ben Von Handorf

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: