Skip to main content

C# - Building a Silverlight Deep Zoom Application [Beginner]


In the first part we looked at how to download hundreds of O'Reilly bookcovers usingC#. In the second part, we saw how to stitch those imagestogether into something a little more friendly for Deep Zoom Composer. In this part, we're going to create a Deep Zoom Composer project, export the final images, and build the finished Silverlight application.

In order to build Deep Zoom applications, you're going to need to download Microsoft's Deep Zoom Composer. Everything else you should already have - especially if you're building Silverlight applications. In case you haven't checked out the previous tutorials yet, below is the application we'll be building today.
[silverlight width="630" height="480" src="/sites/default/files/409/source/OReillyDeepZoom.xap"]

 

Step 1 - Import the Images

Deep Zoom Composer is separated into three parts: Import, Compose, and Export. The first thing we're going to need to do is import all of the O'Reilly book covers.

Deep Zoom Composer
Tabs

Using the application that we created in part2 of this tutorial, my O'Reilly book covers have been combined into 21 rows each containing 38 images. Each row is 19,000 pixels wide and around 1,000 pixels tall. The reason I didn't import each image separately is that Deep Zoom Composer eventually used up a ton of memory and crashed when I attempted to do so. I have not re-tried that option using the latest version, however at the time, there seemed to be a maximum number of images it could handle.

Simply click the "Add Image" button on the right side of the screen and select your images. Once complete, you should have something similar to the image below.

Deep Zoom Composer Images
List

 

Step 1 - Compose the Images

Once we've got the images imported, it's time to compose them into what the final application will look like. Click the compose tab at the top of the page to enter the composition area. Once in there, simply select all the images using the list view at the bottom and drag and drop them onto the canvas.


As you can see, Deep Zoom Composer staggered the images by default, which is not what we want. Fortunately, it's got some nifty tools for arranging images. With all the images selected, right-click one of them to bring up the "Arrange into Grid" dialog.


Since I have 21 rows of images, I set the "Constrain by" option to Rows, the "Number of Rows" option to 21, and the "Padding" to 0 (since I don't want any space between my rows).


Once you click OK on that dialog, Deep Zoom Composer will arrange the images exactly like they're supposed to be.

 

Step 3 - Export Deep Zoom Project

Now that the image are composed how we want, it's time to export them from Deep Zoom Composer to something that can be used by our Silverlight application.


Simply go to the "Custom" tab, set the "Output type" to "Silverlight Deep Zoom", give it a name, choose a location, then hit "Export". All the other default options will work fine for us. The export process will take several minutes, depending on how large your project is.

What Deep Zoom Composer generates for you is a couple of different things. First it will create a folder called "GeneratedImages". This folder contains hundreds of images that Silverlight will request and combine when a user is using the Deep Zoom application. Inside this folder is also a file called "dzc_output.xml". This file will be the actual source of the MultiScaleImage object that will be used when building our app.

 

Step 4 - Build the Silverlight App

Now we're down to the good stuff - actually building up the final application. Once you've got a new Silverlight application ready, the first thing you're going to need to do is get the GeneratedImages folder into your project. I copied and added it the ClientBin folder of the ASP project.


The first piece of code we need to write will create the multiscale image object and set it's source to our Deep Zoom Composer output.
<UserControl x:Class="DeepZoom.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="600" Height="400" Background="Black">
    <Grid x:Name="LayoutRoot" Background="White">
      <MultiScaleImage x:Name="msi" Source="../GeneratedImages/dzc_output.xml"/>
    </Grid>
</UserControl>
 
If you were to actually run this right now, you'd see what looked like a finished, working, application. However, you'll find out quickly that none of the nice mouse gestures work. Unfortunately, these aren't built into the MultiScaleImage object, but Microsoft did provide source code to hook it up. The code-behind for this app looks like this:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace OReillyDeepZoom
{
  public partial class Page : UserControl
  {
    //
    // Based on prior work done by Lutz Gerhard, Peter Blois, and Scott Hanselman
    //

    double zoom = 1;
    bool duringDrag = false;
    bool mouseDown = false;
    Point lastMouseDownPos = new Point();
    Point lastMousePos = new Point();
    Point lastMouseViewPort = new Point();


    public double ZoomFactor
    {
      get { return zoom; }
      set { zoom = value; }
    }

    public Page()
    {
      InitializeComponent();

      //
      // Handling all of the mouse and keyboard functionality
      //
      this.MouseLeftButtonDown += 
        delegate(object sender, MouseButtonEventArgs e)
      {
        lastMouseDownPos = e.GetPosition(msi);
        lastMouseViewPort = msi.ViewportOrigin;

        mouseDown = true;

        msi.CaptureMouse();
      };

      this.MouseLeftButtonUp += delegate(object sender, MouseButtonEventArgs e)
      {
        if (!duringDrag)
        {
          bool shiftDown = 
            (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;
          double newzoom = zoom;

          if (shiftDown)
          {
            newzoom /= 2;
          }
          else
          {
            newzoom *= 2;
          }

          Zoom(newzoom, msi.ElementToLogicalPoint(this.lastMousePos));
        }
        duringDrag = false;
        mouseDown = false;

        msi.ReleaseMouseCapture();
      };

      this.MouseMove += delegate(object sender, MouseEventArgs e)
      {
        lastMousePos = e.GetPosition(msi);
        if (mouseDown && !duringDrag)
        {
          duringDrag = true;
          double w = msi.ViewportWidth;
          Point o = new Point(msi.ViewportOrigin.X, msi.ViewportOrigin.Y);
          msi.UseSprings = false;
          msi.ViewportOrigin = new Point(o.X, o.Y);
          msi.ViewportWidth = w;
          zoom = 1 / w;
          msi.UseSprings = true;
        }

        if (duringDrag)
        {
          Point newPoint = lastMouseViewPort;
          newPoint.X += (lastMouseDownPos.X - lastMousePos.X) / 
            msi.ActualWidth * msi.ViewportWidth;
          newPoint.Y += (lastMouseDownPos.Y - lastMousePos.Y) / 
            msi.ActualWidth * msi.ViewportWidth;
          msi.ViewportOrigin = newPoint;
        }
      };

      new MouseWheelHelper(this).Moved += 
        delegate(object sender, MouseWheelEventArgs e)
      {
        e.Handled = true;

        double newzoom = zoom;

        if (e.Delta < 0)
          newzoom /= 1.3;
        else
          newzoom *= 1.3;

        Zoom(newzoom, msi.ElementToLogicalPoint(this.lastMousePos));
        msi.CaptureMouse();
      };
    }

    private void Zoom(double newzoom, Point p)
    {
      if (newzoom < 0.5)
      {
        newzoom = 0.5;
      }

      msi.ZoomAboutLogicalPoint(newzoom / zoom, p.X, p.Y);
      zoom = newzoom;
    }
  }
}
 
Since I didn't write the code, I'm not going to explain it. You'll just have to copy and paste it into your project. The MouseWheelHelper object comes from a file provided by Microsoft called MouseWheelHelper.cs. You can download this class from the files attached to this tutorial.

If you run the application now, you'll see that all the mouse clicks, drags, and wheel clicks do exactly what they're supposed to. In fact, we have a fully functional Deep Zoom application that matches the example at the beginning of the tutorial.

And that does it for this post. You can download a Visual Studio 2008 project for the example application below (everything except the images).
Source Files:

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as