3 Replies Latest reply on Apr 12, 2007 6:31 AM by peterent

    Add clickable image to Flex

      In my flex-2 design, I have a need to put an image in the program, then define points on the image that trigger events.
      In details, I want a map of the US, where when the user either:
      1- clicks on a state |
      2- mouses over a state
      (I haven't decided)

      An event is thrown that I can popup a box and display some data to the user.

      I don't believe I need to use an SWF pre-generated file to do this, as flex should be able to handle this via AS-3.

        • 1. Re: Add clickable image to Flex
          peterent Level 2
          Here's one way to do it:

          Create a new class, extending Canvas. Into this class place your image (either as MXML or via ActionScript).

          The class should have a UIComponent child added after the Image so that it lies on top of the Image. In either the updateDisplayList function or when the image has loaded (ie, some event to trigger this), create a series of Shape object s(see flash.display.Shape) and add them to the UIComponent.

          Draw your shapes using their graphics properties, but use a solid fill with alpha = 0. You won't get mouse events if don't draw something and the alpha will make them invisible but selectable.

          Add an eventHandler to the UIComponent to capture mouse clicks. The UIComponent will only receive the clicks over the shapes. You can either then dispatch your own event depending on which shape was picked or just let the click event bubble up.

          Note: you can draw directly into the UIComponent's graphics too, but it will be easier to tell where the mouse has been clicked if you use separate shapes.

          Note: if you want to change the cursor to a hand over the shape, set the UIComponent's useHandCursor="true"; its buttonMode="true"; its mouseChildren="false". You have to do all 3 to see the hand cursor.
          • 2. Re: Add clickable image to Flex
            davidledet Level 1
            Great help, Peter.
            One small problem...

            How do I determine which shape was clicked in the UIComponent when handling the "Mouse.CLICKED" event?
            Maybe the problem is Im addling the eventListener at the wrong location.
            Im adding it to the UIcomponent.

            • 3. Re: Add clickable image to Flex
              peterent Level 2
              Do something like this, where shapes is an Array of the Shape you created.

              private function onClick( event:MouseEvent ) : void

              for(var i:int=0; i < shapes.length; i++)
              var sh:Shape = shapes as Shape;
              if( sh.hitTestPoint(event.stageX, event.stageY, true) )
              _selectedItem = hitAreas
              dispatchEvent( new Event("hitClick") );