Monday, March 23, 2009

Silverlight 3 Beta Pixel Shader Effects

This is another nice feature included in Silverlight 3.Pixel shaders are programs which operate at pixel all pixel values(value of A,R,G,B) are passed through the associated pixel shaders before displaying in the screen.Then the pixel shaders will do some calculations and change the pixel value.
For example if we have applied a pixel shader called “Negative” to a StackPanel,then all pixels in the area of that StackPanel will go through Negative pixel shader and it Negate the pixel values by decrementing from 255(255-A,255-R,255-G,255-B).
This is the basic idea of pixel shaders and the Silverlight 3 itself contains 2 Pixel shader effects as of now.They are DropShadow and Blur.

Applying pixel shader Effect

Now the UIElement class in the Silverlight has got a new dependency property called Effect which is the entry point to the pixel shaders.We can directly apply the Effect to this property.Since all the controls and visual elements are inherited from UIElement,they also have the pixel shader support.
Applying DropShadow pixel shader effect through XAML to a Button

<Button HorizontalAlignment="Center" VerticalAlignment="Center" Content="Joy's Button">            <Button.Effect>                <DropShadowEffect Color="Black"                                  ShadowDepth="5" />            </Button.Effect></Button>
C# to Apply DropShadowEffect

private void Button_Click(object sender, RoutedEventArgs e){    btn.Effect = new DropShadowEffect() { Color=Colors.Black,ShadowDepth=5};}

Grouping pixel shader effects

The Silverlight 3 currently doesn’t support grouping of Effects.If we want to apply Blur effect and DropShadow effect to a Button we have to go for a workaround.
  • Wrap the control using a Border.
  • Apply the new effect to the border.

<Border>            <Button HorizontalAlignment="Center"                    VerticalAlignment="Center"                    Content="Joy's Button">                <Button.Effect>                    <DropShadowEffect Color="Black"                                      ShadowDepth="5" />                </Button.Effect>            </Button>            <Border.Effect>                <BlurEffect Radius="5" />            </Border.Effect></Border>

Blur effect has been applied to the Border in order to get more than one effect on the Button.Writing custom pixel shader effects will be discussed later.

No comments: