Geeks With Blogs

News


Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged
Timmy Kokke …just sorting my bubbles…

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>    
 
Posted on Monday, March 2, 2009 3:42 PM WPF | Back to top


Comments on this post: Scratchcard in WPF

# re: Scratchcard in WPF
Requesting Gravatar...
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!
Left by Ben Von Handorf on Mar 14, 2009 12:02 AM

Your comment:
 (will show your gravatar)


Copyright © Timmy Kokke | Powered by: GeeksWithBlogs.net