Pages

Saturday, September 8, 2012

Parallax Background in XAML Revisited

Adapted from the original post Metro Parallax Background in XAML.

Those who are super observant may have noticed that as you scroll through the tiles in the Windows 8 start screen, the background moves at about 1/10th the speed as the foreground. I've heard some people call this a "parallax background". No matter what we call it, I'm sure we all want it in our own Windows 8 app. This post explains one relatively simple way to accomplish this.

Trees

I am assuming that the foreground content is stored within a horizontal scrolling ScrollViewer. Let's give this ScrollViewer a name, like MyScrollViewer. In this demo, the content of the foreground is the front row of trees. The background can be anything: an Image, a Canvas, or in the case of this demo, more (smaller) trees.

I've added a RenderTransform to the background trees that allows me to translate (move) the starting position (x) of the background. I could set the TranslateX of the transform to a constant, or bind it to any value I wish. What I want to do is bind the TranslateX to the HorizontalOffset property of MyScrollViewer.

If I do this, the background will move at the same speed and in the opposite direction of the ScrollViewer. This is because as we scroll to the right and the foreground trees move left, HorizontalOffset increases. Increasing the value of TranslateX casues the background text to move right.

To slow down the background and reverse its direction, we need to multiply HorizontalOffset by something like -0.1 before assigning it to TranslateX. For this we write a converter called ParallaxConverter and apply the converter to the binding.

ParallaxConverter.cs
using System;
using Windows.UI.Xaml.Data;

namespace ParallaxBackgroundLibrary
{
    public class ParallaxConverter : IValueConverter
    {
        const double _factor = -0.10;

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            double factor;
            if (!Double.TryParse(parameter as string, out factor))
            {
                factor = _factor;
            }

            if (value is double)
            {
                return (double)value * factor;
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            double factor;
            if (!Double.TryParse(parameter as string, out factor))
            {
                factor = _factor;
            }

            if (value is double)
            {
                return (double)value / factor;
            }
            return 0;
        }
    }
}

If you look closely at the converter, it accepts a parameters in case you are not particularly pleased with my selection of -0.1. You can also use the parameter to create even more depth in you application by supporting two or more backgrounds with different converter factors. The demo code below demonstrates the use of the converter parameter by constructing two background rows of trees that move at different speeds as you pan left and right.

MainPage.xaml
<Page
   x:Class="ParallaxBackgroundDemoApp.MainPage"
   IsTabStop="false"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="using:ParallaxBackgroundDemoApp"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:pbl="using:ParallaxBackgroundLibrary"
   mc:Ignorable="d">
    <Page.Resources>
        <pbl:ParallaxConverter
           x:Key="ParallaxConverter" />
    </Page.Resources>
    <Grid>
        <Rectangle>
            <Rectangle.Fill>
                <LinearGradientBrush
                   EndPoint="0.5,1"
                   StartPoint="0.5,0">
                    <GradientStop
                       Color="#FF5A8302"
                       Offset="0" />
                    <GradientStop
                       Color="#FFEEEE00"
                       Offset="1" />
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Canvas>
            <local:Trees>
                <local:Trees.RenderTransform>
                    <CompositeTransform
                       TranslateX="{Binding ElementName=MyScrollViewer, Path=HorizontalOffset, Converter={StaticResource ParallaxConverter}}"
                       ScaleX="0.25"
                       ScaleY="0.25" />
                </local:Trees.RenderTransform>
            </local:Trees>
        </Canvas>
        <Rectangle
           Fill="Black"
           Opacity="0.2" />
        <Canvas>
            <local:Trees>
                <local:Trees.RenderTransform>
                    <CompositeTransform
                       TranslateX="{Binding ElementName=MyScrollViewer, Path=HorizontalOffset, Converter={StaticResource ParallaxConverter}, ConverterParameter=-0.2}"
                       ScaleX="0.5"
                       ScaleY="0.5" />
                </local:Trees.RenderTransform>
            </local:Trees>
        </Canvas>
        <Rectangle
           Fill="Black"
           Opacity="0.2" />
        <ScrollViewer
           x:Name="MyScrollViewer"
           HorizontalScrollMode="Enabled"
           HorizontalScrollBarVisibility="Auto">
            <local:Trees />
        </ScrollViewer>
    </Grid>
</Page>

That’s it.

ParallaxBackground binary (basically just the converter) resides here: http://nuget.org/packages/parallaxbackground/

ParallaxBackground source (complete with the demo trees application) resides here: http://parallaxbackground.codeplex.com/

1 comment:

  1. Works great but I'd love to see someone do a sample using just the Visual Studio Grid template application to show how you do this with a GridView as your main content source. I've tried a number of thing but can't seem to make it work.

    ReplyDelete

Note: Only a member of this blog may post a comment.