Create clickable zones in image?

11,502

Solution 1

Thanks you all for your answers, there are interesting things in them.

Unfortunately, as I had to develop this very fast, I just created an image on which I would catch the onclick event and then catch the zones the user clicked using Cursor.Position like this :

int X = pictureBox.PointToClient(Cursor.Position).X;
int Y = pictureBox.PointToClient(Cursor.Position).Y;

Maybe not the "cleaner" way to do it, but it works ! Thanks anyway !

Solution 2

Why don't you just implement something like this?

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class Zone
{
    public Region Region { get; private set; }
    public Action<MouseEventArgs> Click { get; private set; }

    public Zone(Region zoneRegion, Action<MouseEventArgs> click)
    {
        this.Region = zoneRegion;
        this.Click = click;
    }
}

public class PictureBoxWithClickableZones : PictureBox
{
    private readonly List<Zone> zones = new List<Zone>();

    public void AddZone(Zone zone)
    {
        if (zone == null)
            throw new ArgumentNullException("zone");

        this.zones.Add(zone);
    }

    protected override void OnMouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);

        foreach (var zone in this.zones.Where(zone => zone.Region.IsVisible(e.Location)))
            zone.Click(e);
    }
}

If you have enought time you can make appropriate components and use then even in Visual Studio's WinForms Designer.

Solution 3

Although it isn't all that popular anymore, you can use the <map> tag to do this.

<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" />
  <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" />
  <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" />
</map> 

Edit:

Since this requires a WinForms solution, perhaps this article can help you.

C# Windows Forms ImageMap Control

Share:
11,502
BPruvost
Author by

BPruvost

Updated on June 16, 2022

Comments

  • BPruvost
    BPruvost almost 2 years

    I have to implement a solution for which I'm not really sure how to proceed as I don't know this language (C#) very well.

    Let me explain : The goal is to have something that allows the user to choose a zone from an item (which has a circular form). So the idea was put an image with numbers on the zone (so in the end it would look like a clock), and get the zone from the number the user would click.

    So my question is : is it possible to create clickable zones in an image ? (Or if you have another solution for this functionnality, I'm open-minded)

    Thanks in advance !

    EDIT >> This is for a WinForm application, not a website.