Today’s post was written by Matt Casto, a former colleague of mine, and my partner in crime for the Stir Trek event we held last May. You can read more from Matt at http://programwith.net.
Pixel shaders, also known as shader effects, are a cool new feature the became available with Silverlight 3. The two most common effects â€“ drop shadow and blur â€“ are included with Silverlight. Its easy to add these effects to any UIElement.
Lets build upon the simple form that was introduced in Jeffâ€™s post Day #10: Styling Silverlight Controls. We can add a drop shadow effect to the email address textbox by changing the Page.xaml to look like this.
Running the application will show the drop shadow effect has been applied to the textbox.
You can adjust the ShadowDepth, BlurRadius and Direction dependency properties to change the way the effect is rendered. For instance, if we change all of these values to be 10 we end up with this.
Let’s also change the Page.xaml.cs code behind to set a Blur effect on the submit button while the Mailer service is being called.
Run the application now and click Submit after filling in an email address and youâ€™ll see the button get blurry until the service call has completed.
Pixel shaders modify the pixels before theyâ€™re rendered to display. This takes place at runtime and doesnâ€™t use hardware acceleration at this point, so donâ€™t expect these effects to be the most performant.
Adding Your Own Shader
You can create your own pixel shaders using High-Level Shading Language (HLSL) compiled with the DirectX SDK. Or you can download the Shazzam application to create, test and debug your pixel shader. Shazzam was created for WPF but all of these effects should work in Silverlight as well. Note that youâ€™ll need the DirectX SDK installed first.
I pulled the Invert Color sample from Shazzamâ€™s Shader Loader samples into the project by selecting Tools->View Compiled Shaders, copying the file (InvertColor.ps) and pasting it into the SilverlightStyling project. Also, I made sure the build action for the file is set to Resource. I then created a class to load the InvertColor.ps file.
Then I applied the shader to the entire form by adding the effect to the LayoutRoot grid element.
Now our entire form has a beautiful effect.
There are a lot more pixel shaders available from the Windows Presentation Foundation Pixel Shader Effects Library CodePlex project which was updated recently to work with Silverlight 3.