Click here to Skip to main content
15,889,862 members
Articles / Web Development / ASP.NET

Silverlight: Reflection Image Button

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
4 Jul 2009CPOL2 min read 28.4K   16   4
A simple Silverlight control that creates an image button with zoom and reflection

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:

XML
<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:

XML
<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:

C#
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.

C#
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:

C#
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:

XML
<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:

C#
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:

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

... and then pass that through:

C#
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:

XML
<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

This article was originally posted at http://feeds2.feedburner.com/CSharperImage

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager Microsoft
United States United States
Note: articles posted here are independently written and do not represent endorsements nor reflect the views of my employer.

I am a Program Manager for .NET Data at Microsoft. I have been building enterprise software with a focus on line of business web applications for more than two decades. I'm the author of several (now historical) technical books including Designing Silverlight Business Applications and Programming the Windows Runtime by Example. I use the Silverlight book everyday! It props up my monitor to the correct ergonomic height. I have delivered hundreds of technical presentations in dozens of countries around the world and love mentoring other developers. I am co-host of the Microsoft Channel 9 "On .NET" show. In my free time, I maintain a 95% plant-based diet, exercise regularly, hike in the Cascades and thrash Beat Saber levels.

I was diagnosed with young onset Parkinson's Disease in February of 2020. I maintain a blog about my personal journey with the disease at https://strengthwithparkinsons.com/.


Comments and Discussions

 
GeneralSmall question Pin
Shani Natav24-Sep-09 4:58
Shani Natav24-Sep-09 4:58 
GeneralThe code, an example... Pin
cwp4213-Jul-09 8:04
cwp4213-Jul-09 8:04 
GeneralRe: The code, an example... Pin
Anurag Gandhi23-Jul-09 3:36
professionalAnurag Gandhi23-Jul-09 3:36 
GeneralRe: The code, an example... Pin
Jeremy Likness24-Jul-09 9:51
professionalJeremy Likness24-Jul-09 9:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.