Friday, January 29, 2010

Drawing Dashed Lines, Arcs, and Cubic Curves

The ActionScript Graphics class supports drawing solid lines and quadratic curves. But there isn't native support for dashed lines or cubic (Bezier) curves.

I've created a sample application that shows the three line types: straight, quadratic curve and cubic curve. It also lets you choose between showing a solid line, a dashed line, or both. The line thickness can also be adjusted.



I also got a little carried away and added the quadratic and cubic control points as buttons that you can drag around the canvas to change the curve.

Most of the drawing functionality for these examples is in the GraphicsUtils.as class that contains the following static functions:
  • drawLine() - draws a straight line, either solid (using Graphics.lineTo() function) or dashed
  • drawQuadCurve() - draws a quadratic curve, either solid (using Graphics.curveTo() function) or dashed
  • drawCubicCurve() - draws a cubic curve (two control points), either solid or dashed. The curve is an approximation done by dividing the curve into many small segments and drawing straight lines
  • drawCircle() - draws a circle, either solid (using Graphics. drawCircle() function) or dashed
  • drawArc() - draws an arc, either solid or dashed
The dashed lines are drawn by dividing the line into many small segments to draw the dashes. By default a dash length of 10 pixels is used, but that is customizable.

The equations used to calculate the values at any point along the line for the three cases were found on the Wikipedia entry for Bézier curves.

Tuesday, January 26, 2010

Flex Context Menus

I've had some frustration with Flex ContextMenus, so I thought I'd write an entry about the basics of creating context menus, adding items, listening for context menu events, and a few restrictions on context menus.

Every InteractiveObject (e.g. Application, Panel, Button, etc) contains a contextMenu property. For most components it will be null and you'll have to create a new menu and assign it to that property. So you can have different context menus for different components.

Here is a simple example of a context menu set on the application:


Here is a short snippet from the above example showing you have to create a ContextMenu, hide the built-in menu items, and listen for menu events.
private function initContextMenu():void {
    // 1. Create the context menu if it doesn't exist
    // it will exist for the application, but won't for most other components
    if (!contextMenu) {
        this.contextMenu = new ContextMenu();
    }

    // 2. Hide the built-in menu items 
    // (you can't remove the basic 3 or 4 items like: Settings, About, etc)
    contextMenu.hideBuiltInItems();
    
    // 3. Add menu items, you can optionally set the menu item enablement and
    // visibility in the ContextMenuItem constructor
    var firstItem:ContextMenuItem  = new ContextMenuItem("Hello there!"true);
    contextMenu.customItems.push(firstItem);
    var secondItem:ContextMenuItem = new ContextMenuItem("Disabled");
    contextMenu.customItems.push(secondItem);
    var thirdItem:ContextMenuItem = new ContextMenuItem("Hidden");
    contextMenu.customItems.push(thirdItem);
    
    // 4. Listen for menu events
    // this event happens when the context menu is about to show
    contextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, 
        function(event:ContextMenuEvent):void {
            // add logic here to determine the visibility or enablement
            secondItem.enabled = false;
            thirdItem.visible = false;
        });
    
    // 5. Handle menu item click events
    var handler:Function = function(event:ContextMenuEvent):void {
        Alert.show("You clicked on the menu item '" 
                    event.currentTarget.caption + "'");
    };
    firstItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handler);
    secondItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handler);
    thirdItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handler);
}

There are many restrictions to Flex ContextMenus, some of which will drive you crazy. Read carefully, it will save you time later.
  • Maximum of 15 custom menu items in the menu
  • No sub-menus allowed
  • No icons in menus
  • Menu items must be 100 characters or less
  • Control characters, newlines, and other white space characters are ignored
  • MANY reserved words including (but not limited to):
    • Save
    • Zoom In
    • Zoom Out
    • 100%
    • Show All
    • Quality
    • Play
    • Loop
    • Rewind
    • Forward
    • Back
    • Movie not loaded
    • About
    • Print
    • Show Redraw Regions
    • Debugger
    • Undo
    • Cut
    • Copy
    • Paste
    • Delete
    • Select All
    • Open
    • Open in new window
    • Copy link
    • Copy Link Location
    • Del
I'm not quite sure why there are so many restrictions, but I'm sure Adobe has a good reason for it!

More details about the restrictions can be found on the ContextMenuItem page.

There are a few other solutions for people who want more control over the menus. These usually involve adding right click listeners in JavaScript on top of the Flex application and passing that event into Flex to position and show a custom menu instead of the usual Flex context menu.
Here is one such solution: Custom Context Menu.
These solutions can work quite effectively, but since they depend on the browser they can be quite buggy.


Wednesday, November 4, 2009

Pass ...rest as a parameter to another function

I recently needed to have a function that accepted a variable number of parameters. This can easily be accomplished using the function myFunction(...rest) syntax. This way I can pass in no parameters (in which case rest is an empty array), one parameter, or multiple parameters.

But, then I wanted to pass those same parameters on to another function that also accepted a variable number of parameters (e.g. ExternalInterface.call(jsFunctionName, ...args)). If you simply call the other function and pass in rest as a parameter then it won't work as expected. E.g.
    public function sayHello(...rest):void {
        // this won't work as expected
        callMe(rest);
    }
    
    private function callMe(...rest):void {
        trace(rest.length + ": ['" + rest.join("' | '""']");
    }

What happens in callMe(...rest) is rest is an array that actually contains only one item - another array which has the rest parameters that were originally passed into sayHello(...rest).
So if you made a call like this:
    sayHello("Hello""World""!");
Then the traced output would be 1: ['Hello,World,!'].
Notice that there is only 1 parameter!

The way to get around this is to use Function.apply(null, args) to call the function instead, like this:
    public function sayHello2(...rest):void {
        // use Function.apply to pass in the rest parameters properly
        var func:Function = callMe; 
        func.apply(null, rest);
    }

So if you made this call now:
    sayHello2("Hello""World""!");
Then the traced output would be 3: ['Hello' | 'World' | '!'].
Now there are 3 parameters as expected.

I found some help on this topic from The Joy Of Flex Blog by David Colleta.

Friday, October 23, 2009

LineChart with CheckBox Legend (Filter Series)

The following example shows a LineChart with a custom Legend that has CheckBoxes next to each LegendItem which allows you to filter the Chart to only show certain series (in this case lines).

I've created a custom class called CheckBoxLegend which extends Legend. It sets the legendItemClass to be the flex.utils.ui.charts.CheckBoxLegendItem class which extends the default LegendItem to add the CheckBox on the left side of the legend item.

Clicking on the legend item toggles the CheckBox and updates the Chart to show or hide the corresponding series. The series is hidden by setting the alpha value to 0.

Here is a snippet of how you use it in MXML:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:charts="flex.utils.ui.charts.*">

<mx:LineChart id="linechart" ... />
<charts:CheckBoxLegend dataProvider="{linechart}"
    color="#000000" direction="horizontal"/>

</mx:Application>

Here is the example, right click to view source:


Note that the minimum and maximum values of the vertical axis don't get updated when you uncheck one or more series. The Axis calculates these values but doesn't take into account the visibility of the Series. So I've added a new Update Vertical Axis Min/Max CheckBox that will go through all the y axis number values and calculate the minimum and maximum values for the visible series. I haven't tested this out on complicated datasets or different chart types, but hopefully it will be a good starting point.

Originally I played around with actually removing the series from the chart (instead of hiding it), but that caused more problems because when you remove a series the chart will automatically re-color any of the remaining series (unless you specified the stroke/color/fill styles) and the legend gets re-populated without the unchecked series. So it was easiest to just hide the series.

Thursday, October 22, 2009

Elevation Map using USGS and Yahoo Maps

** January 2012 Update
Yahoo has officially shut down support for Flex maps, so this example no longer works. For other options try the Google Flash Maps component (which is also deprecated now too)


This example combines two different services:
  • Flex Yahoo Maps - shows an interactive map component similar to Google Maps (Flex 3).
  • USGS Elevation Service - gets the elevation at a given Latitude and Longitude.

  • The Flex application below has the Yahoo Maps component on top and an AreaChart below which will show the elevation.
    Click on the map to add a marker. When you click again in a different location another marker is added, and the elevation chart at the bottom will show the elevation profile for the two points. If you want a more fine-grained elevation profile you can use the drop-down menu above the elevation chart to adjust how frequently the elevation is looked up (every KM, every 500m, every 200m). Keep in mind that the more elevations you look up the slower it is.

    You can also search for an address too using the search bar. The elevation at the search location will be displayed in the toolbar to the right of the search button. You can also show kilometer markers as well by checking the Show KM Markers checkbox in the top toolbar.

    Feel free to use this code for your own purposes. All you have to do is sign up for a Yahoo Maps key here:
    https://developer.apps.yahoo.com/wsregapp/
    And then edit the ElevationMapFunctions.as file and put your key in the APPID constant.
    Here is the Yahoo Maps API.

    There are also a few custom markers included in the source code that you can use and/or modify for your own needs.

    Use the mouse scroll wheel to zoom in or out (or use the +/- control on the map).

    This is a very simple example and a lot more could be done with it. It's really just to show how to get elevation data from the USGS Web Service, and how to add markers to a Yahoo Map.


    ** November 2009 Update
    I've updated the example to include another custom marker - the TitleMarker. This marker shows a label on the marker when it is collapsed. I've also added the option of Showing KM Markers which are displayed as TitleMarkers.
    I also separated the Elevation code into separate packages, and added some operations to allow querying for multiple elevations in sequence. When an elevation is returned from the USGS web service it is cached in the ElevationService class to speed things up.

    ** January 2010 Update
    I've restricted the number of elevations that can be looked up at one time to 30. This is to prevent someone trying to lookup the elevation every 200m between Canada and Europe. If you download the source code, and get your own yahoo maps application id then you can do what you like!

    ** January 2012 Update
    Yahoo has officially shut down support for Flex maps, so this example no longer works. For other options try the Google Flash Maps component (which is also deprecated now too)