Silverlight

Silverlight3 is out!

Author: Steve
Posted on: 10 Jul 2009
Silverlight3 is out and we work on new SvFx 3.0 version release with some great stuff supporting new Silverlight 3.0 features.

Expect new SvFx 3.0 release published soon.

Below is short change log of new features in SvFx 3.0, we mainly worked on SL3 features support.

Carousel Control

- New Coverflow location setup (completely based on SL3 features) with advanced settings: reflection, blur, angles, item spacings, etc.
- Reflection support for carousel items (check HasReflections check box inside demo)
- Blur support for carousel items (check CanUseBlur check box inside demo)
- Tween support for carousel animation
- Improved animation of items


SlideShowControl

- New pixel shader based patterns: Water, Ripple, Fade and more...


TextEffects

- Support for multi line text animation
- Support for animation by words
- Pixel shader based animations
- Support for style defined text block properties

+ Bug fixes.

I'm very excited about 3.0 version we are going to release soon!

Posted in: Silverlight

ZLib for Silverlight

Author: Steve
Posted on: 02 Jul 2009
ZLib library for Silverlight. Easily read and write ZLib streams. Full source code available.

ZLib streams can be easily read and written via SvZLib library.

Add Cellbi.SvZLib using and use Utils class which contains compression and decompression methods.

Full source code can be downloaded here:

Cellbi.SvZLib-Source

Let me know what you think.

Posted in: Silverlight

Text Effects in Silverlight - It's So Simple

Author: Steve
Posted on: 28 May 2009
In this blog post I'm going to concentrate on how text animation control can be used and customized to create lot's of different text animations.

Download: TextEffectsSample Source

Text animation is powerful tool to present information and catch visitors attention. There are several libraries out there to create text animations in Flex. If you need to create text effects in Silverlight apps - please try SvLite Effects.

See it in action below:

SvLite Effects library providers text effect control to create text animations in Silverlight. The control is easy to use and can be configured in multiple ways to create different text animations.

TextEffectControl can be defined in Xaml as follows:

 <SvUx:TextEffectControl 
x:Name="textEffect"
Text="Text Effects"
FontSize="40"
HorizontalAlignment="Center"
VerticalAlignment="Center" />

You need to set it's Text property, FontSize and it's also possible to use custom Style for the control. In the above code we use TextEffectControlStyle defined inside application resources dictionary.

To start text animation you can use two methods: Show - to show text, and Hide - to hide text. However you also need to define animation parameters for the control. This can be done by setting text effect control Pattern property.

Text effect control Pattern property has TextAnimationPattern type and it defines type of show and hide animations for all text characters.

The following xaml code shows simple text animation pattern, which defines relatively complex animation:

 <SvFx:TextAnimationPattern >
<SvFx:TextAnimationPattern.AnimationSelectors >
<SvFx:AllAnimationGroupSelector >
<SvFx:AllAnimationGroupSelector.AnimationPattern >
<SvFx:ShiftItemPattern
ShowInterval="0.1"
HideInterval="0.1"
SpeedRatio="4"
Shuffle="True"
MoveTween="BackTweenOut"
ShiftMode="FromRandomPoint"
StartVerticalOffset="60"
StartHorizontalOffset="60" />
</SvFx:AllAnimationGroupSelector.AnimationPattern>
</SvFx:AllAnimationGroupSelector>
</SvFx:TextAnimationPattern.AnimationSelectors>
</SvFx:TextAnimationPattern>

AnimationSelectors property defines animation groups and in the above code we use AllAnimationGroupSelector to apply animation to the whole text. In the above code we also use ShiftItemPattern for the selector. ShiftItemPattern is really powerful tool to customize your animations. Shift item pattern contains lot's of properties to customize animation.

Just open App.xaml file from the post's sample code and take a look into all animation patterns defined. It's so simpe!

Posted in: Silverlight

Create Reflection Shader in Silverlight

Author: Steve
Posted on: 25 May 2009
In this post I'm going to post some sample code on how to create reflection shader using new pixel shader feature of Silverlight 3.

Reflection Shader Source

It is easy to create pixel shaders in Silverlight. It's basically C# like code. Language for creating shaders is called HLSL - High Level Shader Language. HLSL is heavily used inside video games to create cool graphics :) At the moment Silverlight doesn't allow you to define vertex shaders, you can do only pixel.

See how it works:

Steps to Create New Pixel Shader:

  1. Create new text file with "fx" extension and place your HLSL code there.
  2. Then compile (not with Visual Studio, but with special effect compiler tool available from DirectX SDK - you can download this from Microsoft web site) your "fx" file to get compiled pixel shader. Compiled pixel shader is placed inside binary file with "ps" extension.
  3. Make sure to include this "ps" file into your project and set it's compile type to "Resource".
  4. And finally create new ".cs" file and place C# shader code there.

Fx File

Effect file should contains HLSL instructions in order to compile. If you are new to HLSL then read HLSL reference here: HLSL Reference it should give you information on language syntax, available data types, operators and functions.

Here is how simplest "fx" file looks like:

sampler2D input : register(s0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
  return tex2D(input, uv);
}

This line: "sampler2D input : register(s0);" defines "input" variable of sampler2D type. This instruction "register(s0)" defines that data for input variable comes from "s0" register. Next main function is defined - it's C like syntax, except for "TEXTCOORD" and "COLOR" - these are HLSL semantics used by effect compiler and GPU. TEXTCOORD means that "uv" parameter contains texture coordinates, which can get values from 0 to 1. Since "uv" variable has float2 data type, it's possible to access it's "u" and "v" components, e.g. "uv.u", "uv.v", or you can use "uv.x", "uv.y". COLOR semantic means that main function returns color data. "text2D" used inside main function's body is HLSL function which returns color data from the given sampler and texture coordinates.

We are going to define Reflect function for our reflection shader. See below:

float4 Reflect(float2 uv : TEXCOORD) : COLOR
{
  float edge = 0.5;
  if (uv.y > edge)
  {
    uv.y = edge - (uv.y - edge);
    return tex2D(input, uv) * uv.y;
  }
  return tex2D(input, uv);
}

 

The code is really simple, if uv.y > 0.5 we reflect uv coordinate and return color data, otherwise we use original texture coordinate to return color data. So now we just call Reflect function from our main:

float4 main(float2 uv : TEXCOORD) : COLOR
{
  return Reflect(uv);
}

To compile fx code you need to run the following command line:
fxc /T ps_2_0 /E main /Fo "Reflection.ps" "Reflection.fx"

For more info see this:
Fxc Tool

You can define pre build action for your project:
"fxc" /T ps_2_0 /E main /Fo "$(ProjectDir)Reflection.ps" "$(ProjectDir)Reflection.fx"

fxc tool will create "Reflection.ps" binary file - include it to your project and set compile type to resource.

 

C# Shader File

Create new C# file, and paste the following code:

 

using System;
using System.Windows.Media.Effects;
using System.Windows;

namespace ReflectionShader
{
  public class ReflectionShader : ShaderEffect
  {
    public ReflectionShader()
    {
      Uri u = new Uri(@"ReflectionShader;component/Reflection.ps", UriKind.Relative);
      PixelShader = new PixelShader() { UriSource = u };
    }

    public static readonly DependencyProperty ElementHeightProperty =
            DependencyProperty.Register("ElementHeight",
            typeof(double), typeof(ReflectionShader),
            new PropertyMetadata(100.0, OnElementHeightChanged));

    static void OnElementHeightChanged(DependencyObject d, 
      DependencyPropertyChangedEventArgs e)
    {
      (d as ReflectionShader).OnElementHeightChanged((double)e.OldValue, (double)e.NewValue);
    }

    protected virtual void OnElementHeightChanged(double oldValue, double newValue)
    {
      PaddingBottom = newValue;
    }

    public double ElementHeight
    {
      get { return (double)base.GetValue(ElementHeightProperty); }
      set { base.SetValue(ElementHeightProperty, value); }
    }
  }
}

Take a look at the code inside ReflectionShader constructor - it sets PixelShader property inherited from ShaderEffect class. "ReflectionShader;component/Reflection.ps" - this string sets relative url to our "ps" file. Since reflection shader needs some space below ui element we use PaddingBottom property inside OnElementHeightChanged method.

 

Hot to Use Pixel Shader

It's really simple. Here is Xaml code:

 <Button 
x:Name="btnReflected"
Width="200"
Height="70" >
<TextBlock
FontWeight="Bold"
FontSize="25"
Text="Reflection" />
<Button.Effect >
<local:ReflectionShader
ElementHeight="70" />
</Button.Effect>
</Button>


That's all.

Posted in: Silverlight

Silverlight Visual States Sample

Author: Steve
Posted on: 06 Apr 2009
In this article I want to illustrate interesting aspect of Silverlight visual states and how they can be used in controls. It is not a secret that one of the key features in Silverlight controls is an ability to declare different states for a control and specify transitions between them.

Each transition between states can take time for animation and often it is necessary to know when transition is really finished.

Let us suppose that we've spent a couple of hours and prepared simple button in Blend.
Something that looks like the following picture ;-)

Visual States Image

The button above consists from 3 parts: LayoutRoot (grid with Width and Height bound to the "Width" and "Height properties of control), Host (button background with color property bound to the "Background" property of control) and Content (green arrow).

You can see how it works here:

Here is the result of such efforts in xaml code, which specifies simple style for the button. The following xaml shows visual state manager and visual states.

 <vsm:VisualStateManager.VisualStateGroups >
<vsm:VisualStateGroup
x:Name="CommonStates" >
<vsm:VisualStateGroup.Transitions >
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000"
To="MouseOver" />
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000"
To="Play" />
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000" />
</vsm:VisualStateGroup.Transitions>
<vsm:VisualState
x:Name="Normal" >
<Storyboard />
</vsm:VisualState>
<vsm:VisualState
x:Name="MouseOver" >
<Storyboard >
<DoubleAnimationUsingKeyFrames
BeginTime="00:00:00"
Duration="00:00:00.4000000"
Storyboard.TargetName="Host"
Storyboard.TargetProperty="(UIElement.Opacity)" >
<SplineDoubleKeyFrame
KeyTime="00:00:00"
Value="1" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
<vsm:VisualState
x:Name="Play" >
<Storyboard >
<DoubleAnimationUsingKeyFrames
BeginTime="00:00:00"
Duration="00:00:00.4000000"
Storyboard.TargetName="Host"
Storyboard.TargetProperty="(UIElement.Opacity)" >
<SplineDoubleKeyFrame
KeyTime="00:00:00"
Value="0" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>

Now we need to add behaviour logic to this button. It should have 2 methods: Start and Stop.
When mouse is moved over the button the Host should change its opacity. When Stop method is called or button is simply clicked the Content should start rotation - play state of the button.

So, from the point of implementation this can be done in the following way. As you can see from the picture, the Button contains 3 states: "Normal", "MouseOver" and "Play". When mouse pointer is moved over the control we should start transition to the MouseOver state and when the button is clicked we should start transition to the Play state and only after that start the rotation of content.

Please note: "only after that" start the rotation of the content ;) The problem is that transitions between the states can take a time. And if you start rotation of the content immediately after the button is clicked - it will occur in parallel mode with transition and trust me it will look really ugly. So to avoid this we definitely should start the rotation after the transition is finished.

Silverlight has easy way to do exactly this. We can use visual state manager and visual states. Xaml code contains VisualStateManager which declares VisualStates and Transitions. So implement our task we simply need to get access to the VisualStateGroups in the OnApplyTemplate method override and handle several events. Lets take a look how the code would look like.

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();

  FrameworkElement root = GetTemplateChild("LayoutRoot") as FrameworkElement;

  .........

  commonStatesGroup = GetVisualStateGroup(root, "CommonStates");
  HookVisualStateGroupEvents(commonStatesGroup);
}

VisualStateGroup GetVisualStateGroup(FrameworkElement root, string groupName)
{
  if (root == null)
    return null;

  IList groups = VisualStateManager.GetVisualStateGroups(root);
  if (groups == null)
    return null;

  foreach (VisualStateGroup gr in groups)
    if (gr != null && gr.Name == groupName)
      return gr;

  return null;
}

void HookVisualStateGroupEvents(VisualStateGroup group)
{
  if (group == null)
    return;
  group.CurrentStateChanged += group_CurrentStateChanged;
}

void group_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
{
  if (e.NewState != null && e.NewState.Name == "Play")
    OnStarted();
}

Now let's see what is done in the above code.

First we get access to the "CommonStates" visual group in the OnApplyTemplate method and then simply subscribe to CurrentStateChanged event.

VisualStateChangedEventArgs in the handler gives us only 3 properties: Control, OldState and NewState. However this is all we need in this handler. ;-)

When our event handler is called we can say that control was animated and we know which states animation was done for.

From this point we know that state of the control was changed and we can start content rotation.

Source

I hope this sample will be useful.

Posted in: Silverlight

Silverlight Effect Samples

Author: Steve
Posted on: 27 Mar 2009
We recently worked on new samples of Silverlight effects and ad banner done completely in Silverlight. Now these samples are published on the web site.

Silverlight platform get's mature pretty quickly, with new Silverlight3 features we are going to create stunning effect controls :-)

It's really great experience to code with Silverlight. We wecently worked on new samples of Silverlight effects and we now use banner done completely in Silverlight. You can view ad banner here: SvLite Effects.

SvLite Effects helps you create stunning animations for your web site. The library contains high level animation controls such as Carousel, SlideShow, TextEffectControl, ItemsAnimationControl and others. These controls are easy to use from xaml or procedural code.

Just take a look at the following samples showing several animation effects created with SvLite Effects. (you will need Silverlight installed to view these samples)

Please give me your feedback!!!

 

Posted in: Silverlight

Silverlight Slide Control

Author: Steve
Posted on: 05 Mar 2009
This post contains source code for a simple slide in/out control built in Silverlight.

First of all let's look at the sample below:

Move mouse over blue rectangle and control content will slide out.

Such control can preserve some visual space needed for application and it's really easy to use. Just drop it inside xaml and set GripWidth property.

Control style can be also easily changed inside generic.xaml file.

Here is the code illustrating how slide control can be used on a page:

 <local:SimpleSlideControl 
GripWidth="20" />

Below is the code for the the slide control template:

 <Style 
TargetType="local:SimpleSlideControl" >
<Setter
Property="Template" >
<Setter.Value >
<ControlTemplate
TargetType="local:SimpleSlideControl" >
<Canvas
x:Name="host" >
<StackPanel
x:Name="panel"
Orientation="Horizontal" >
<ContentControl
Content="{TemplateBinding Content}" />
<Rectangle
x:Name="grip"
Fill="Blue"
Width="{TemplateBinding GripWidth}" />
</StackPanel>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

If you want to change grip style - just remove "grip" rectangle and replace it with something more appropriate.

Source

I hope it will be helpful ;)

Posted in: Silverlight

Create Change Events for Silverlight Properties

Author: Steve
Posted on: 26 Feb 2009
This post shows how you can create property changed event if such event is missing from base class. When you need property change event for some property defined inside a base class library you may try this trick. This is specific for Silverlight and uses template bindings.

Let's consider e.g. Silverlight Control class. When you create any custom control you may need to know when Control class properties are changed.

Control class has several font related properties, however there is no property changed event for any of those properties.

If you need to get event when e.g. FontSize property is changed you can use the following trick:

Create special purpose control which will define property changed event:

public class MyEventControl : Control
{
  public static readonly DependencyProperty FontSizeSourceProperty = 
    DependencyProperty.Register("FontSizeSource", typeof(double), typeof(MyEventControl),
      new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
      
  public MyEventControl()
  {
  }
  
  static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  {
    (obj as MyEventControl).OnPropertyChanged(e);
  }

  void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
  {
    if (PropertyChanged == null)
      return;
    PropertyChanged(this, e);
  }
  
  public double FontSizeSource
  {
    get { return (double)GetValue(FontSizeSourceProperty); }
    set { SetValue(FontSizeSourceProperty, value); }
  }

  public event DependencyPropertyChangedEventHandler PropertyChanged;
}

The code above is very simple: one dependency property, which we'll use as a source, plus event.

Next you need to use this control inside style for your custom control. Style means Xaml code :)

Put it into Xaml code and bind FontSizeSource property to FontSize:

 <local:MyEventControl 
x:Name="eventControl"
FontSizeSource="{TemplateBinding FontSize}" />

That's it. Now you can obtain eventControl instance inside OnApplyTemplate method in your custom control and use PropertyChanged event:

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();
  eventControl = GetTemplateChild("eventControl") as MyEventControl;
  if (eventControl != null)
    eventControl.PropertyChanged += new DependencyPropertyChangedEventHandler(ehPropertyChanged);
}

Now when control's FontSize property is changed we'll get ehPropertyChanged event handler called. Thanks to template binding we used inside xaml!

Posted in: Silverlight