Tuesday 6 November 2007

A Silverlight Image Map

I've been preparing one of my sessions for DDD, and trying to bring new and fresh samples for the talk. One of my aims is that even if you have seen a Silverlight session before, you will come away with some new and useful knowledge.

In my talk I will obviously cover the Image tag in XAML, which led me to creating a crude little image map as demonstrated by the XAML below:



<!-- An Image Map -->
<Canvas Visibility="Visible"
Canvas.Left="20" Canvas.Top="200">
<Image x:Name="myImage"
Source="../../Assets/Images/WeeMee.JPG">
</Image>
<Rectangle x:Name="leftEye"
Canvas.Left="42" Canvas.Top="48"
Height="12" Width="10"
Cursor="Hand"
Stroke="Black" StrokeThickness="2" Fill="Red" Opacity="0"
MouseLeftButtonDown="OnEyeClick"
>
</Rectangle>
<Rectangle x:Name="rightEye"
Canvas.Left="57" Canvas.Top="48"
Height="12" Width="10"
Cursor="Hand"
Stroke="Black" StrokeThickness="2" Fill="Red" Opacity="0"
MouseLeftButtonDown="OnEyeClick"
>
</Rectangle>
</Canvas>


The key to how this works is, the rectangles being the click points. I.e. Its an image with 2 rectangles overlaying the image. By setting the opacity to 0, it makes the rectangles act as a hotspot even though its not visible.

Please note that I have used a fill, as the default fill is transparent, and therefore the center of the rectangle is not hittable, so it needs to be a solidcolorbrush.

Anyways I will demo this for DDD, and I will probably make it a little snazzier than it is just now.

2 comments:

Anonymous said...

Thanks for the tips here. This helped me get started for the task at hand!!

Jelgab said...

Thanks for the tip. In my case, I needed to have a different URL to go to, for each "Image Map Zone", so I put each URL in the "Tag" property of each rectangle and then processed in the click event like this:

private void MapLinkClick( Object TheClickedLinkSender, MouseButtonEventArgs e )
{
Rectangle TheClickedLink;

//The sender is a rectangle:
TheClickedLink = (Rectangle) TheClickedLinkSender;

//Do anything with the obtained URL:
TheMessage.Content = TheClickedLink.Tag.ToString();
}