Decrease Font Size
Increase Font Size
   BLOG

Silverlight - Creating Image Map with Hotspots

Create Hot spots with Silverlight | Silvelright image Hotspots| Silverlight image hotspots| Silverlight image hot region| Silverlight image map, Silverlight pen tools

Introduction

Recently I was working on a Silverlight application and one of the pages contains a graphic. One of the requirements is that the graphic should contain clickable regions (Hotspots) and display a dynamic navigation menu when the end users click on it. An image that contains one or more Hotspots or clickable area is called an image map. I have put together a simple tutorial on how to get this done.

Getting Started

Image map can be created by using Microsoft Expression Design or Expression Blend.

  1. If you do not have Microsoft Expression Design, you can download a trial version from here.
  2. If you do not have Microsoft Expression Blend, you can download a trial version from here.

Microsoft Expression Designer

Prepare your favorite image. In this tutorial, I used a map graphic to demonstrate that we can create Hotspots in different shapes with Microsoft Expression Designer/ Blend. I downloaded a random map from here. Follow the step from below.

  1. Open Microsoft Expression Design 3
  2. Go to File, New, Fill up all the information and click the OK button.
  3. Go to View, check Snap to Points and Snap to Pixels.
  4. File, Import Image, and browse for your image and click the Open button.
  5. Double click on the Layer1 and rename it to MainImage.

At this point, you should see something like below.

Figure 1
Main Image

Add a new layer at the top of MainImage layer, highlight it and select the Pen tool and draw a hotspot around Russia.

Figure 2

New layer
Pen Tool Russia

Double click the Layer 2 and name it Russia or something meaningful so we can utilize it in the Silverlight application. Highlight the points and click on the properties tab. See below.

Figure 3

Add property

Pick a color you like and set it Opacity to 40%.

Figure 4

Set opacity

After you have finished drawing the Hotspots, click on File, Export and copy the setting from below.

Figure 5

Export

Putting everything together

Open Visual Studio 2008, go to File, New, Project, and choose the Silverlight Application template. If you don't have the Silverlight Controls Toolkit, you can download it from here. Make sure you have added the reference for System.Windows.Controls.Toolkit. Open the MainPage.xaml and drag a Viewbox control on to the page. This control will stretch the map image inside it proportionally when we resize the browser. Then copy the content in the MapsHotSpot.xaml into the Viewbox content in the MainPage.xaml. See below.

Listing 1

<UserControl x:Class="MapsHotspotDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"> 
  <Grid x:Name="LayoutRoot">
        <controlsToolkit:Viewbox  x:Name="MapsViewbox"  >
<!-- Maps content here -->
               <Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    x:Name="MapsHotSpot" Width="800" 
                    Height="600" Clip="F1 M 0,0L 800,0L 800,600L 0,600L 0,0" 
                    UseLayoutRounding="False">
			...
		   </Canvas>
<!-- End Maps content here -->
        </controlsToolkit:Viewbox>
  </Grid>
</UserControl>

Expression Blend

If you choose to do it by using Expression Blend, here are the steps to follow.

  1. Open Microsoft Expression Blend.
  2. Click on File, select New Project and follow the setup from below.

Figure 6

Blend New Project

Add a Viewbox into the LayoutRoot and name it MapsViewbox, then add a Canvas inside the Viewbox and name it MapsHotspot. After that, add a Canvas into MapsHotspot and an Image control into the Canvas. From the Image control properties, specify the image source and setup the appropriate width and height of the image. Then, create another Canvas and name it Russia or something meaningful or unique. Make sure that the width and height of the newly created Canvas match the image in order to draw points on it. Click on the Pen tool and draw points or vertices around Russia. Pick a brush color and set it Opacity to certain percentages. Repeat the same procedure for the rest of the countries.

Figure 7

Blend Hot Spot

Tooltips

Remember that we named each layer at the beginning. The layers and points are translated into Canvas and Path objects respectively when we export them into XAML. We can provide each layer with a unique name or include a tag attribute to it and use it to pull the country information from a database or resource dictionaries. For simplification sake, we will have a method to loop through each child elements in the MapsHotSpot Canvas, grab their name and set it to the tooltip content. Attach a MouseMove event to each layer to highlight the country on mouse hover. Also, attach a MouseLeftButtonUp event to pop up a menu when the left mouse button is released. See Listing 2.

Listing 2

foreach (Canvas c in (this.FindName("MapsHotSpot") as Canvas).Children)
            {
                if (!string.IsNullOrEmpty(c.Name))
                {
                    c.Cursor = Cursors.Hand;
                    ToolTip toolTip = new ToolTip { Content = c.Name };
                    c.SetValue(ToolTipService.ToolTipProperty, toolTip);
	c.MouseMove += new MouseEventHandler(c_MouseMove);
                    c.MouseLeftButtonUp += new 			 	MouseButtonEventHandler(c_MouseLeftButtonUp);
                }
            }

Displayed below is the implementation of the c_MouseMove method. This method will highlight the Canvas/ country and clear the previous selection, if there is any, during mouse hover event.

Listing 3

void c_MouseMove(object sender, MouseEventArgs e)
        {
            Canvas c = sender as Canvas;
            ResetLastSelected();
            if (!string.IsNullOrEmpty(c.Name))
            {
                lastSelected = c.Name;
                SetCanvasColor(c, Color.FromArgb(255, 92, 112, 171), 2, Colors.Green);
            }
        }

View in browser, you should see something like below. If you resize the browser, you will still see the full map. Place the mouse over the map image to see the tooltip and the highlighted region.

Figure 8

Preview

We will build a simple menu with several links in it. First, add a simple class to hold the link properties. See below for an example.

Listing 4

public class Links
    {
        public string Title { get; set; }
        public string URL { get; set; }
        public Links(string t, string u)
        {
            Title = t;
            URL = u;
        }
    }

After that, create a global List (T) class to hold the link objects and populates the link class with the below data on page load.

Listing 5

private List<Links> _links = new List<Links>();
void SetupLinks()
        {
            _links.Add(new Links("About the people", "http://www.countryreports.org/{0}.aspx"));
            _links.Add(new Links("Economy", "http://www.economicexpert.com/a/{0}.htm"));
            _links.Add(new Links("Global Statistics", "http://www.geohive.com/cntry/{0}.aspx"));
            _links.Add(new Links("Population", "http://www.geohive.com/charts/population1.aspx"));
            _links.Add(new Links("Wiki", "http://en.wikipedia.org/wiki/{0}"));
        }

Below is the implementation of the c_MouseLeftButtonUp method. This method will bring up the popup menu by calling the PopulateContextMenu method in response to the mouse left button click event. The PopulateContextMenu take a country name as an argument, loop through the list of link objects and concatenate the country name to it. The purpose of the PositionContextMenu method is to set the popup menu position. I also added animation to fade in and fade out the popup menu, please refer to the MainPage.xaml.

Listing 6

void c_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Canvas c = sender as Canvas;
            if (!string.IsNullOrEmpty(c.Name))
            {
                PopulateContextMenu(c.Name);
                PositionContextMenu(e.GetPosition(contextMenu.Parent as UIElement), true);
                e.Handled = true;
            }
        }
        void PositionContextMenu(Point p, bool useTransition)
        {
            if (useTransition)
                contextMenu.IsOpen = false;
            contextMenu.HorizontalOffset = p.X;
            contextMenu.VerticalOffset = p.Y;
            contextMenu.IsOpen = true;
        }
void PopulateContextMenu(string country)
        {
            contextListBox.Items.Clear();
            foreach (Links l in _links)
            {
                HyperlinkButton hlb = new HyperlinkButton();
                hlb.Content = l.Title;
                hlb.NavigateUri = new Uri(string.Format(l.URL, country));
                hlb.TargetName = "_blank";
                contextListBox.Items.Add(hlb);
            }   
        }

At this point, you should see something like below.

Figure 9

Mouse click map

The final piece is to hide the popup menu and clear the highlighted country once we click on the non- clickable area of the map image. In order to achieve that, we can attach a MouseLeftButtonUp event to the Layout grid on page load. See below.

Listing 7

LayoutRoot.MouseLeftButtonUp += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonUp);
void LayoutRoot_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {      
            ResetLastSelected();
            HideMenu();
        }
        void HideMenu()
        {
            HidePopup.Begin();
            contextMenu.HorizontalOffset = -50.0;
        }

Points of Interest

Initially I was planning to use the right mouse button click event class that I found from here to trigger the popup menu, but I decided to leave it out after reading an article from here about its disadvantages.

I found this article useful although it was written in VB.NET and I can't get it to compile, but I'm able to utilize the logic embedded in it.

Conclusion

If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and explore it in order to grasp the full concept of it because I might left out some useful information. I hope someone will find this article useful on how to create image Hotspots or map on any images.

Resources

Adding right click to Silverlight
Limitations of Windowless mode for Silverlight
Silverlight - World Map

Watch this script in action

Demo

Downloads

Download

Comments (57) -

  • Veneers Melbourne

    10/22/2009 1:58:44 PM |

    Good post I really appreciate your work man thanks a lot for this great post.

  • electric heating uk

    10/26/2009 10:36:17 PM |

    You really shared a very valuable post with us i inspired with your work thanks.

  • Ink Cartridges

    10/28/2009 4:22:08 AM |

    I have to download silverlight latest version and then I will also work on it. Thanks for that and till then your post help me and trained me for that. Smile

  • Send Flowers to Pakistan

    11/11/2009 7:29:54 AM |

    I really appreciate your work man thanks a lot for this great post.

  • Gucci Belts

    11/13/2009 9:18:53 PM |

    Great insight after all to increase the required data interpretation and all above.

  • sports bottle

    11/16/2009 6:22:39 PM |

    I am looking for a map that will let me know what cities are within a 6 and a half hour driving time from my home town. Is there any online maps that allow me to do this?

  • sensual photography

    11/20/2009 1:17:36 AM |

    Be careful not to make the image too small that you lose any specific detail you are trying to display. In other words, you are basically going to have to play around with what works.

  • cheap printer ink

    11/22/2009 10:51:48 AM |

    Hi,
       Why didn’t I find this post earlier? Keep up the good work!

  • Promotional Folders

    11/22/2009 7:10:31 PM |

    I have Microsoft Expression Web and I also have professionally designed templates from Design Template. I have downloaded some templates to my computer and unzipped the files and I have no idea on how to successfully load them to Microsoft Expression web. I understand that FTP maybe involved - but I'm not experienced and I would really appreciate some very easy to follow instructions.

  • web design brisbane

    11/22/2009 7:40:52 PM |

    I hear d that Silver light now allows us to create rich interactive applications for the Web using Visual...is it true..

  • send flowers uk

    11/24/2009 6:29:59 PM |

    Really nice and helpful post. I always appreciate topics like these being discussed to aware people. thanks for sharing.

  • luxury beach rentals

    11/26/2009 1:03:19 AM |

    If I am creating a silverlight video game and I want to handle multiple keydown events, like a player pressing the right and up arrow buttons at the same time, how do I do that, since KeyEventArgs only gives me the latest button that was pressed?

  • trophy melbourne

    11/26/2009 3:03:16 AM |

    The map you share with us is really help me a lot...I really appreciate your work...

  • jewelry wholesaler

    11/26/2009 10:19:57 AM |

    Here i m looking for the advantages of using Microsoft share point designer when creating a website?

  • eye cosmetic surgery

    12/2/2009 3:20:06 PM |

    As screwed up a job as they do - at least Microsoft puts out updates, upgrades, and patches. Meanwhile, the world has as many glitches in it as it ever had - viruses, conflicts, corruption, malfunctioning systems, etc.

  • Budget Van Lines

    12/3/2009 11:01:26 AM |

    i always wondered how these are coded..awesome

  • icon editor

    12/7/2009 10:52:39 AM |

    Be careful not to make the image too small that you lose any specific detail you are trying to display. In other words, you are basically going to have to play around with what works.

  • St patricks day decorations

    12/8/2009 12:56:33 AM |

    Very valuable information you share with us through this post....very appreciating work...

  • Reglage couleurs

    12/13/2009 4:51:58 AM |

    Nice post...Its really useful for color correction

  • redimensionner photo

    12/14/2009 10:28:12 AM |

    Just wanted to give you a shout from the valley of the sun, great information. Much appreciated

  • small business seo services

    12/29/2009 5:56:07 PM |

    I understand that FTP maybe involved - but I'm not experienced and I would really appreciate some very easy to follow instructions.

  • jasminlive

    12/31/2009 12:03:26 PM |

    Well, the post is actually the freshest topic on this registry related issue. I fit in with your conclusions and will thirstily look forward to your coming updates. Just saying thanks will not just be sufficient, for the phenomenal lucidity in your writing. I will right away grab your rss feed to stay abreast of any updates.

  • Send Flowers to Pakistan

    1/7/2010 9:08:21 AM |

    what cities are within a 6 and a half hour driving time from my home town. Is there any online maps that allow me to do this? That is the best thing.

  • Gucci Belts

    1/7/2010 9:35:06 AM |

    I have to download silver light latest version and then I will also work on it. That the best possible way after all.

  • small to medium business websites

    1/7/2010 12:19:11 PM |

    I appreciate topics like these being discussed to aware people. thanks for sharing.

  • rowing kit

    1/27/2010 9:40:13 PM |

    Nice article......I was searching these kind of information ,Thank you so much.....

  • redimensionner photo

    1/28/2010 4:50:50 AM |

    hi.......Awesome post! Interesting info to know.            

  • Imeye Review

    2/4/2010 1:57:22 AM |

    Although they do put out a lot of updates I do find Microsoft Expression difficult to get to grips with. Great tutorial though.

  • Fran

    2/4/2010 8:12:46 PM |

    Let me say it in smple words - wow!! I wasn't aware that something like this is possible with silverlight - or any other application. With this freedom in shapes, I directly feel some ideas entering my mind. I will have to investigate in Silverlight....

  • best digital camera

    2/7/2010 2:40:38 AM |

      Top post. I look forward to reading more. Cheers

  • pizza press

    2/8/2010 2:18:22 AM |

    Image maps done with hotspots makes work easier. You shared a knowledge here enough for the newbies and the experts to like.

  • free online dating services

    2/8/2010 4:53:46 AM |

    I contain to download silver light newest version and then I will also work on it. Thanks for your post assist me and trained me for that. Smile

  • 1000 Questions For Couples Review

    2/8/2010 7:51:23 PM |

    Thanks. Very informative post about silverlight.

  • liza antony

    2/14/2010 11:11:51 AM |

    Silver light work like this i never expected or never seen anythg iformative finally i stop by your post and read whole it was worth reading just wow Smile

  • Rob

    2/26/2010 1:16:05 AM |

    I like that you outlined Russia Smile my backround is Russian Smile

  • geld lenen

    3/16/2010 3:25:17 AM |

    I really like your work thanks a lot for this great post.

  • Oliver

    4/22/2010 11:22:23 PM |

    It seems like silverlight is picking up in popularity

  • Bradly

    4/23/2010 9:19:13 PM |

    Love your blog I am heading to subscribe

  • Web Hosting Reviews

    5/22/2010 7:49:05 AM |

    Gr8 tutorial..!! thanks a ton for haring such informative tutorial. going to cr8 a map right now

  • ray thomasn

    6/20/2010 7:53:14 AM |

    this is my second time i visit here.

    I discovered so many fascinating stuff in your pages especially it's discussion.

    From the loads of comments on your articles, I assume I am not the only one having all the enjoyment here!

    Keep up the good work. Thanks a lot !!

    Have a  Happy  day !!

  • Greener Life

    6/20/2010 4:48:51 PM |

    Thanks for nice tutorial.

  • Learn Internet

    6/26/2010 11:24:43 AM |

    This is a great tutorial. It explained very wonderfully to the some of the points for Silverlight..
    Thanks for sharing......

  • Crisstian

    8/24/2010 3:49:24 AM |

    Hey, I guess Silverlight is a really great pice of software, isn't it ?
    I am kind of new to it, but I hope to become very familiar to this great Microsoft platform.
    Thanks!

  • geld lenen

    9/15/2010 6:11:12 PM |

    This a real nice example, I just build my first little application with silverlight and I think it's great piece of software that i'm going to use more in the future.

  • marko

    9/22/2010 9:24:38 AM |

    Yeah, starting to love the silverlight

  • Kara R

    10/7/2010 1:09:26 PM |

    It took me a while but i think i'm managing to get to grips with silverlight, it certainly has a lot of potential!

  • Jogos Infantis

    10/28/2010 6:52:22 AM |

    Love it, but I wish this was easier to find. Took me like 33 minutes to find on Google - otherwise, top notch!

  • Free Movies

    11/21/2010 6:12:24 PM |

    This is a great tutorial. It explained very wonderfully to the some of the points for Silverlight..
    Thanks for sharing......

  • larry smith

    12/3/2010 8:13:53 AM |

    I stubled upon this page: wow! I really need your guide man, thanks.

  • obagi

    12/19/2010 4:16:06 PM |

    silverlight is new to me, so i appreciate the post, thanks.

  • Lasik Singapore

    12/21/2010 8:17:32 AM |

    Thanks for the guide. I admit I'm still a silverlight newbie.

  • Fran Hammil

    12/28/2010 8:05:36 PM |

    Nice tutorial and guide here!

  • Sliema Hotels

    12/30/2010 1:20:46 AM |

    Very good tutorial, thanks for sharing

  • Employee Database

    1/1/2011 1:29:11 AM |

    Wow, I never knew about this blog before. That's pretty interesting.

  • homework helper

    1/2/2011 7:53:18 AM |

    This article was extremely interesting, especially since I was searching for thoughts on this subject last week.

  • tv

    1/5/2011 7:19:30 PM |

    Nice tutorial, thanks

  • green laser pointer

    2/4/2011 4:28:21 PM |

    wow, it is a great topic, and i like the blogs Smile

Pingbacks and trackbacks (5)+

Add comment

Loading