Saturday, July 10, 2010

Create custom context menu using Actionscript 3

Sometimes it is needed to change the default context menu. Although you can't remove right clicking, you can modify the menu items.

Take a look at the example, right click to change the color of the square:



Here's the commented code, have fun with it:

// create the square
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0,0,200,200);
square.graphics.endFill();
addChild(square);

var my_menu:ContextMenu = new ContextMenu();// set your context menu
my_menu.hideBuiltInItems();// hide the built in menu items, such as Play, etc.

// create menu items
var color1=new ContextMenuItem("Change color to red");
var color2=new ContextMenuItem("Change color to blue");
my_menu.customItems.push(color1, color2);

// make a new ColorTransform (to change color of the square later)
var c:ColorTransform = new ColorTransform();

// first item function
function doRed(e:ContextMenuEvent):void {
 c.color=0xFF0000
 square.transform.colorTransform = c
}
color1.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, doRed);

// second item function
function doBlue(e:ContextMenuEvent):void {
 c.color=0x0033FF
 square.transform.colorTransform = c
}
color2.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, doBlue);

// apply the context menu
contextMenu = my_menu;

Context menu items don't always have to have a functionality, it can just be a line of text. If you don't want the item to do anything, don't make any event listeners for it.

No comments:

Post a Comment