Windows Phone 7 : Dragging and flicking UI controls

Posted by TechTwaddle on Geeks with Blogs See other posts from Geeks with Blogs or by TechTwaddle
Published on Sun, 19 Dec 2010 17:18:09 GMT Indexed on 2010/12/20 17:49 UTC
Read the original article Hit count: 286

Filed under:

Who would want to flick and drag UI controls!? There might not be many use cases but I think some concepts here are worthy of a post.

So we will create a simple silverlight application for windows phone 7, containing a canvas element on which we’ll place a button control and an image and then, as the title says, drag and flick the controls. Here’s Mainpage.xaml,

  1. <Grid x:Name="LayoutRoot" Background="Transparent">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="Auto"/>
  4.     <RowDefinition Height="*"/>
  5.   </Grid.RowDefinitions>
  6.  
  7.   <!--TitlePanel contains the name of the application and page title-->
  8.   <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
  9.     <TextBlock x:Name="ApplicationTitle" Text="KINETICS" Style="{StaticResource PhoneTextNormalStyle}"/>
  10.     <TextBlock x:Name="PageTitle" Text="drag and flick" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
  11.   </StackPanel>
  12.  
  13.   <!--ContentPanel - place additional content here-->
  14.   <Grid x:Name="ContentPanel" Grid.Row="1" >
  15.     <Canvas x:Name="MainCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
  16.       <Canvas.Background>
  17.         <LinearGradientBrush StartPoint="0 0" EndPoint="0 1">
  18.           <GradientStop Offset="0" Color="Black"/>
  19.           <GradientStop Offset="1.5" Color="BlanchedAlmond"/>
  20.         </LinearGradientBrush>
  21.       </Canvas.Background>
  22.     </Canvas>
  23.   </Grid>
  24. </Grid>

the second row in the main grid contains a canvas element, MainCanvas, with its horizontal and vertical alignment set to stretch so that it occupies the entire grid. The canvas background is a linear gradient brush starting with Black and ending with BlanchedAlmond. We’ll add the button and image control to this canvas at run time.

Moving to Mainpage.xaml.cs the Mainpage class contains the following members,

  1. public partial class MainPage : PhoneApplicationPage
  2. {
  3.     Button FlickButton;
  4.     Image FlickImage;
  5.  
  6.     FrameworkElement ElemToMove = null;
  7.     double ElemVelX, ElemVelY;
  8.  
  9.     const double SPEED_FACTOR = 60;
  10.  
  11.     DispatcherTimer timer;

FlickButton and FlickImage are the controls that we’ll add to the canvas. ElemToMove, ElemVelX and ElemVelY will be used by the timer callback to move the ui control. SPEED_FACTOR is used to scale the velocities of ui controls.

Here’s the Mainpage constructor,

  1. // Constructor
  2. public MainPage()
  3. {
  4.     InitializeComponent();
  5.  
  6.     AddButtonToCanvas();
  7.  
  8.     AddImageToCanvas();
  9.  
  10.     timer = new DispatcherTimer();
  11.     timer.Interval = TimeSpan.FromMilliseconds(35);
  12.     timer.Tick += new EventHandler(OnTimerTick);
  13. }

We’ll look at those AddButton and AddImage functions in a moment. The constructor initializes a timer which fires every 35 milliseconds, this timer will be started after the flick gesture completes with some inertia.

Back to AddButton and AddImage functions,

  1. void AddButtonToCanvas()
  2. {
  3.     LinearGradientBrush brush;
  4.     GradientStop stop1, stop2;
  5.  
  6.     Random rand = new Random(DateTime.Now.Millisecond);
  7.  
  8.     FlickButton = new Button();
  9.     FlickButton.Content = "";
  10.     FlickButton.Width = 100;
  11.     FlickButton.Height = 100;
  12.  
  13.     brush = new LinearGradientBrush();
  14.     brush.StartPoint = new Point(0, 0);
  15.     brush.EndPoint = new Point(0, 1);
  16.  
  17.     stop1 = new GradientStop();
  18.     stop1.Offset = 0;
  19.     stop1.Color = Colors.White;
  20.  
  21.     stop2 = new GradientStop();
  22.     stop2.Offset = 1;
  23.     stop2.Color = (Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color;
  24.  
  25.     brush.GradientStops.Add(stop1);
  26.     brush.GradientStops.Add(stop2);
  27.  
  28.     FlickButton.Background = brush;
  29.  
  30.     Canvas.SetTop(FlickButton, rand.Next(0, 400));
  31.     Canvas.SetLeft(FlickButton, rand.Next(0, 200));
  32.  
  33.     MainCanvas.Children.Add(FlickButton);
  34.  
  35.     //subscribe to events
  36.     FlickButton.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);
  37.     FlickButton.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted);
  38. }

this function is basically glorifying a simple task. After creating the button and setting its height and width, its background is set to a linear gradient brush. The direction of the gradient is from top towards bottom and notice that the second stop color is the PhoneAccentColor, which changes along with the theme of the device. The line,

    stop2.Color = (Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color;

does the magic of extracting the PhoneAccentBrush from application’s resources, getting its color and assigning it to the gradient stop.

AddImage function is straight forward in comparison,

  1. void AddImageToCanvas()
  2. {
  3.     Random rand = new Random(DateTime.Now.Millisecond);
  4.  
  5.     FlickImage = new Image();
  6.     FlickImage.Source = new BitmapImage(new Uri("/images/Marble.png", UriKind.Relative));
  7.  
  8.     Canvas.SetTop(FlickImage, rand.Next(0, 400));
  9.     Canvas.SetLeft(FlickImage, rand.Next(0, 200));
  10.  
  11.     MainCanvas.Children.Add(FlickImage);
  12.  
  13.     //subscribe to events
  14.     FlickImage.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDelta);
  15.     FlickImage.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompleted);
  16. }

The ManipulationDelta and ManipulationCompleted handlers are same for both the button and the image.

OnManipulationDelta() should look familiar, a similar implementation was used in the previous post,

  1. void OnManipulationDelta(object sender, ManipulationDeltaEventArgs args)
  2. {
  3.     FrameworkElement Elem = sender as FrameworkElement;
  4.  
  5.     double Left = Canvas.GetLeft(Elem);
  6.     double Top = Canvas.GetTop(Elem);
  7.  
  8.     Left += args.DeltaManipulation.Translation.X;
  9.     Top += args.DeltaManipulation.Translation.Y;
  10.  
  11.     //check for bounds
  12.     if (Left < 0)
  13.     {
  14.         Left = 0;
  15.     }
  16.     else if (Left > (MainCanvas.ActualWidth - Elem.ActualWidth))
  17.     {
  18.         Left = MainCanvas.ActualWidth - Elem.ActualWidth;
  19.     }
  20.  
  21.     if (Top < 0)
  22.     {
  23.         Top = 0;
  24.     }
  25.     else if (Top > (MainCanvas.ActualHeight - Elem.ActualHeight))
  26.     {
  27.         Top = MainCanvas.ActualHeight - Elem.ActualHeight;
  28.     }
  29.  
  30.     Canvas.SetLeft(Elem, Left);
  31.     Canvas.SetTop(Elem, Top);
  32. }

all it does is calculate the control’s position, check for bounds and then set the top and left of the control.

OnManipulationCompleted() is more interesting because here we need to check if the gesture completed with any inertia and if it did, start the timer and continue to move the ui control until it comes to a halt slowly,

  1. void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs args)
  2. {
  3.     FrameworkElement Elem = sender as FrameworkElement;
  4.  
  5.     if (args.IsInertial)
  6.     {
  7.         ElemToMove = Elem;
  8.  
  9.         Debug.WriteLine("Linear VelX:{0:0.00}  VelY:{1:0.00}", args.FinalVelocities.LinearVelocity.X,
  10.             args.FinalVelocities.LinearVelocity.Y);
  11.  
  12.         ElemVelX = args.FinalVelocities.LinearVelocity.X / SPEED_FACTOR;
  13.         ElemVelY = args.FinalVelocities.LinearVelocity.Y / SPEED_FACTOR;
  14.  
  15.         timer.Start();
  16.     }
  17. }

ManipulationCompletedEventArgs contains a member, IsInertial, which is set to true if the manipulation was completed with some inertia. args.FinalVelocities.LinearVelocity.X and .Y will contain the velocities along the X and Y axis. We need to scale down these values so they can be used to increment the ui control’s position sensibly. A reference to the ui control is stored in ElemToMove and the velocities are stored as well, these will be used in the timer callback to access the ui control. And finally, we start the timer.

The timer callback function is as follows,

  1. void OnTimerTick(object sender, EventArgs e)
  2. {
  3.     if (null != ElemToMove)
  4.     {
  5.         double Left, Top;
  6.         Left = Canvas.GetLeft(ElemToMove);
  7.         Top = Canvas.GetTop(ElemToMove);
  8.  
  9.         Left += ElemVelX;
  10.         Top += ElemVelY;
  11.  
  12.         //check for bounds
  13.         if (Left < 0)
  14.         {
  15.             Left = 0;
  16.             ElemVelX *= -1;
  17.         }
  18.         else if (Left > (MainCanvas.ActualWidth - ElemToMove.ActualWidth))
  19.         {
  20.             Left = MainCanvas.ActualWidth - ElemToMove.ActualWidth;
  21.             ElemVelX *= -1;
  22.         }
  23.  
  24.         if (Top < 0)
  25.         {
  26.             Top = 0;
  27.             ElemVelY *= -1;
  28.         }
  29.         else if (Top > (MainCanvas.ActualHeight - ElemToMove.ActualHeight))
  30.         {
  31.             Top = MainCanvas.ActualHeight - ElemToMove.ActualHeight;
  32.             ElemVelY *= -1;
  33.         }
  34.  
  35.         Canvas.SetLeft(ElemToMove, Left);
  36.         Canvas.SetTop(ElemToMove, Top);
  37.  
  38.         //reduce x,y velocities gradually
  39.         ElemVelX *= 0.9;
  40.         ElemVelY *= 0.9;
  41.  
  42.         //when velocities become too low, break
  43.         if (Math.Abs(ElemVelX) < 1.0 && Math.Abs(ElemVelY) < 1.0)
  44.         {
  45.             timer.Stop();
  46.             ElemToMove = null;
  47.         }
  48.     }
  49. }

if ElemToMove is not null, we get the top and left values of the control and increment the values with their X and Y velocities. Check for bounds, and if the control goes out of bounds we reverse its velocity. Towards the end, the velocities are reduced by 10% every time the timer callback is called, and if the velocities reach too low values the timer is stopped and ElemToMove is made null.

Here’s a short video of the program, the video is a little dodgy because my display driver refuses to run the animations smoothly. The flicks aren’t always recognised but the program should run well on an actual device (or a pc with better configuration),

You can download the source code from here: ButtonDragAndFlick.zip

© Geeks with Blogs or respective owner