Tuesday, June 30, 2009

Silverlight: Reflection Image Button

In continuing with building on Silverlight, I was working on a control strip that contains images. We want to style them fancy, and the "reflection" pattern seems to be quite popular. Applying a reflection to an image is fairly straightforward. My preference is to flip the image and apply an opacity mask:

     <Image x:Name="Reflection" RenderTransformOrigin="0.0,0.0">
            <Image.RenderTransform>
                <ScaleTransform x:Name="ReflectionTransform" ScaleY="-1"/>
            </Image.RenderTransform>         
            <Image.OpacityMask>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#00000000" Offset="0.0"/>
                    <GradientStop Color="#55555555" Offset="1.0"/>
                </LinearGradientBrush>
            </Image.OpacityMask>
        </Image>

Some people prefer a stronger gradient but you get the idea - turn it over and fade it out. If you wanted to get really fancy, you could do a SkewTranform and cast the reflection at an angle.

The next thing I wanted to do was emphasize the solid image a bit when hovered to indicate it is "active." I tried a typical "bouncy" algorithm that moved the image up and down, but personally I prefer scaling the image instead. There are plenty of examples of "zoom toolbars" out there. For our purposes, we'll just barely expand the image to show it is selected, and do it using an animation so it's smooth and doesn't just suddenly pop up. The animations for expanding and contracting are simple:

<Image.Resources>
    <Storyboard x:Name="ImageExpand">
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleX"
                         From="1.0" To="1.1"/>
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleY"
                         From="1.0" To="1.1"/>
    </Storyboard>
    <Storyboard x:Name="ImageContract">
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleX"
                         From="1.1" To="1.0"/>
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleY"
                         From="1.1" To="1.0"/>
    </Storyboard>
</Image.Resources>

When initializing the control, we want to hook into the events for these animations completing so we can stop them for reuse:

public ReflectedZoomImage()
{
    InitializeComponent();           
    ImageExpand.Completed += _AnimationCompleted;
    ImageContract.Completed += _AnimationCompleted;
}

The _AnimationCompleted simply determines who triggered the call and then stops the animation and sets the final scale value - it could have been separate methods but we may eventually want to handle it generically by checking if sender is a storyboard, etc.

private void _AnimationCompleted(object sender, EventArgs e)
{
    if (sender == ImageExpand)
    {
        ImageExpand.Stop();
        MainTransform.ScaleX = 1.1;
        MainTransform.ScaleY = 1.1;
    }
    else if (sender == ImageContract)
    {
        ImageContract.Stop();
        MainTransform.ScaleX = 1.0;
        MainTransform.ScaleY = 1.0;
    }
}

Next, we wire in the events for mouse enter and mouse leave. We want to make sure an existing animation is not already firing before we start it over, so the code for expanding the image looks like this:

private void MainImage_MouseEnter(object sender, MouseEventArgs e)
{
    if (ImageExpand.GetCurrentState().Equals(ClockState.Stopped))
    {
        ImageExpand.Begin();
    }
}

Finally, I wanted to encapsulate this all into a control that I could reuse. The completed XAML for the control looks like this:

<UserControl x:Class="SilverTest.Controls.ReflectedZoomImage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    >
    <Grid x:Name="ReflectionGrid">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Image MouseEnter="MainImage_MouseEnter" MouseLeave="MainImage_MouseLeave" MouseLeftButtonDown="MainImage_MouseLeftButtonDown" x:Name="MainImage" Grid.Row="0">
            <Image.RenderTransform>
                <ScaleTransform x:Name="MainTransform"/>
            </Image.RenderTransform>
<Image.Resources>
    <Storyboard x:Name="ImageExpand">
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleX"
                         From="1.0" To="1.1"/>
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleY"
                         From="1.0" To="1.1"/>
    </Storyboard>
    <Storyboard x:Name="ImageContract">
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleX"
                         From="1.1" To="1.0"/>
        <DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="MainTransform" Storyboard.TargetProperty="ScaleY"
                         From="1.1" To="1.0"/>
    </Storyboard>
</Image.Resources>
        </Image>
        <Image x:Name="Reflection" RenderTransformOrigin="0.0,0.0" Grid.Row="1">
            <Image.RenderTransform>
                <ScaleTransform x:Name="ReflectionTransform" ScaleY="-1"/>
            </Image.RenderTransform>         
            <Image.OpacityMask>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#00000000" Offset="0.0"/>
                    <GradientStop Color="#55555555" Offset="1.0"/>
                </LinearGradientBrush>
            </Image.OpacityMask>
        </Image>
    </Grid>
</UserControl>

To actually use the control, we need to expose a property so the consumer can set the image. I made a property called "ReflectionSource" and once that's set, I can wire it into the main image and the reflection and also set the heights:

public ImageSource ReflectionSource
{
    get
    {
        return MainImage.Source;
    }

    set
    {
        MainImage.Source = value;
        Reflection.Source = value;
        _ControlInit();
    }
}

private void _ControlInit()
{
    MainImage.Width = Width;
    MainImage.Height = Height / 2;

    MainTransform.CenterX = MainImage.Width/2;
    MainTransform.CenterY = MainImage.Height/2; 

    Reflection.Width = Width;
    Reflection.Height = Height / 2;
    
    ReflectionTransform.CenterX = Reflection.Width / 2;
    ReflectionTransform.CenterY = Reflection.Height / 2; 
}

If you noticed in the XAML, I wired into the "MouseLeftButton" event so we can register a click. I expose this as an actual Click event:

...
public event EventHandler<MouseButtonEventArgs> Click; 
...

... and then pass that through:

private void MainImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (Click != null)
    {
        Click(this, e); 
    }
}

Now I can reuse the control ... in this case, I've styled an "up" and "down" image, and put them next to each other with a spacer, like this:

<Border Background="White" CornerRadius="30" Margin="2" Grid.Column="1" Grid.Row="0">
    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="1">
        <silvertest:ReflectedZoomImage Width="21" Height="42" Click="ReflectedZoomImage_Click" ReflectionSource="../Resources/green.png"/>
        <Rectangle Opacity="0" Width="5"/>
        <silvertest:ReflectedZoomImage Width="21" Height="42" Click="ReflectedZoomImage_Click" ReflectionSource="../Resources/red.png"/>
    </StackPanel>
</Border>

Note wiring into the click event and that I can set the width and height of the actual, rendered control, not the individual image (the image is 21, so the rendered control should be 42 to account for the reflection).

The finished product:

Reflected Zoom Image

...and with the red button emphasized:

Reflected Zoom Image 2

And there you have a simple Silverlight user control that takes advantage of the animation and transformation functionality that is built-in to the framework.

Jeremy Likness