Decrease Font Size
Increase Font Size
   BLOG

Silverlight - Creating Image Map with Hotspots

by bryian 28. December 2009 16:56

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

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

Veneers Melbourne

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

Veneers Melbourne United States

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

electric heating uk

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

electric heating uk India

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

Ink Cartridges

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

Ink Cartridges United Kingdom

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

Send Flowers to Pakistan

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

Send Flowers to Pakistan United States

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

Gucci Belts

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

Gucci Belts United States

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

sports bottle

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?

sports bottle India

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

sensual photography

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.

sensual photography India

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

cheap printer ink

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

cheap printer ink United States

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

Promotional Folders

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.

Promotional Folders India

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

web design brisbane

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

web design brisbane India

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

send flowers uk

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

send flowers uk United States

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

luxury beach rentals

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?

luxury beach rentals United States

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

trophy melbourne

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

trophy melbourne India

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

jewelry wholesaler

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

jewelry wholesaler India

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

eye cosmetic surgery

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.

eye cosmetic surgery India

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

Budget Van Lines

i always wondered how these are coded..awesome

Budget Van Lines United States

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

icon editor

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.

icon editor United States

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

St patricks day decorations

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

St patricks day decorations India

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

Reglage couleurs

Nice post...Its really useful for color correction

Reglage couleurs United States

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

redimensionner photo

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

redimensionner photo United States

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

small business seo services

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

small business seo services India

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

jasminlive

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.

jasminlive United States

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

Send Flowers to Pakistan

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.

Send Flowers to Pakistan India

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

Gucci Belts

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

Gucci Belts India

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

small to medium business websites

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

small to medium business websites India

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

rowing kit

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

rowing kit United States

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

redimensionner photo

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

redimensionner photo United States

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

Imeye Review

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

Imeye Review United Kingdom

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

Fran

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

Fran Germany

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

best digital camera

  Top post. I look forward to reading more. Cheers

best digital camera United States

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

pizza press

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

pizza press United States

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

free online dating services

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

free online dating services United States

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

1000 Questions For Couples Review

Thanks. Very informative post about silverlight.

1000 Questions For Couples Review United Kingdom

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

liza antony

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

liza antony United States

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

Rob

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

Rob Canada

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

geld lenen

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

geld lenen Netherlands

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

Oliver

It seems like silverlight is picking up in popularity

Oliver United States

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

Bradly

Love your blog I am heading to subscribe

Bradly Morocco

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

Web Hosting Reviews

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

Web Hosting Reviews United States

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

ray thomasn

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

ray thomasn United States

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

Greener Life

Thanks for nice tutorial.

Greener Life United Kingdom

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

Learn Internet

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

Learn Internet

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

Crisstian

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!

Crisstian Paraguay

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

geld lenen

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.

geld lenen Netherlands

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

marko

Yeah, starting to love the silverlight

marko United Kingdom

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

Kara R

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

Kara R United Kingdom

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

Jogos Infantis

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

Jogos Infantis United States

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

Free Movies

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

Free Movies Islamic Republic of Pakistan

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

larry smith

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

larry smith United States

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

obagi

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

obagi United States

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

Lasik Singapore

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

Lasik Singapore United States

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

Fran Hammil

Nice tutorial and guide here!

Fran Hammil Taiwan

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

Sliema Hotels

Very good tutorial, thanks for sharing

Sliema Hotels United Kingdom

1/1/2011 1:29:11 AM #

Employee Database

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

Employee Database United States

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

homework helper

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

homework helper United States

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

tv

Nice tutorial, thanks

tv United States

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

green laser pointer

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

green laser pointer People's Republic of China

Pingbacks and trackbacks (5)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading