Friday, April 6, 2012

Interactive drawing in MATLAB: Part 1

Being able to draw in the plots/images in MATLAB GUI can be very useful at times. 

MATLAB has a collection of Utilities for Interactive Tools which allows you to place points, lines, rectangles, ellipses, etc on to an axes, so be sure to check them out first to see if they meet your need. 


There are many ways to incorporate/initiate/activate the various drawing tools in MATLAB GUI. You can simply call the functions in the callback of the various uicontrols such as push buttons, drop-down menu, etc. 


In the example that I am about to show, I attach a context menu to the axes, which allows the user to select the desired shape and begin drawing.

1. Create a new MATLAB GUI using the GUI with Axes and Menu template.

2. In the GUIDE window, bring up the Menu editor by Clicking Tools -> Menu Editor.

3. By default, the menu window is in Menu Bar mode, select Context Menus tab at the button of the menu editor.

4. Create the menu items as follows
    a. create a top level menu and name* it cm_axes, this menu item is to be attached to the axes
    b. under the cm_axes menu, create a new menu item and name it cm_draw, this menu item acts as a container of all the possible shapes that you can draw.
    c. under the cm_draw menu, create a new menu item and name it cm_draw_line, once selected, this menu item should allow the user to draw a line
    d. again, under the cm_draw menu, create a new menu item and name it cm_draw_rect, once selected, this menu item should allow the user to draw a rectangle.
    e. repeat d to implement another other shapes that you would like to use.

* By naming a item, I meant changing the item's tag, not labels. The labels of the items can be anything as long as it makes sense.

5. Once the context menu is created, the next step is to attach the context menu to the axes. To do that, simply open up the property editor of the axes, find UIContextMenu, and select cm_axes from the drop down menu.

6. After saving the file, the various callbacks for the menu item should appear at the bottom of your m-file editor. For the menu items cm_draw_line and cm_draw_rectangle, simply insert the two functions imline and imrect, respectively.

7. Save all file, and run the GUI, right click anywhere on the axes to bring up the context menu.

Video walkthrough



Source File

Download the files here.


No comments:

Post a Comment