专题八 MATLAB图形用户界面设计
一 图形窗口与坐标轴
1. 图形对象的句柄
1.1 句柄的概念
在MATLAB中,每一个具体的图形都是由若干个不同的图形对象组成的。
在MATLAB中,用句柄来标识对象,通过句柄来访问相应对象的属性。
1.2 访问图形对象
访问图形对象是指获取或设置图形对象的属性。不同图形对象所具有的属性不同,但访问的方法是一样的。一般使用点运算符来访问对象属性。如下:
对象句柄 . 属性名
例1。
得到结果图为:
可以通过修改图形对象的属性来改变上图,如下:
1.3 获取特定图形对象句柄的函数
- gcf:获取当前图形窗口的句柄。
- gca:获取当前坐标轴的句柄。
- gco:获取最近被选中的图形对象的句柄。
- findobj:按照指定的属性来获取图形对象的句柄。
2. 图形对象的属性
2.1 图形对象的常用公共属性
- Children属性:该对象的所有子对象的句柄组成的一个向量。
- Parent属性:该对象的父对象的句柄。
- Type属性:对象的类型,这是一个只读属性。
- Tag属性:用于给对象定义一个标识符。
例2:分别在两个子图中绘制曲线和曲面。然后设置子图1的背景色为黄色,曲线线条的颜色为红色,设置子图2的背景色为青色。
subplot(1,2,1);
h1 = fplot(@(t)t.*sin(t), @(t)t.*cos(t), [0, 6*pi]); % h1是曲线的句柄
axis equal;
subplot(1,2,2);
[x, y, z] = peaks(20);
h2 = mesh(x, y, z); % h2是曲面的句柄
h10 = h1.Parent; % h10是曲线父对象的句柄,即坐标轴的句柄
h10.Color = 'y'; % 设置坐标轴的颜色为黄色
h1.Color = 'r'; % 设置曲线的颜色为红色
h2.Parent.Color = 'cyan'; % 设置坐标轴的颜色为青色
2.2 图形对象的常用动态属性
- KeyPressFcn属性:定义按下键盘按键事件的响应。
- CreateFcn属性:定义创建图形对象时做出的响应。
- DeleteFcn属性:定义取消图形对象时做出的响应。
- WindowButtonDownFcn或ButtonDownFcn属性:定义单击鼠标左键事件的响应。
3. 图形窗口的操作
3.1 建立图形窗口对象
MATLAB通过figure函数来创建窗口对象,其调用格式为:
- 句柄变量=figure(属性1, 属性值1, 属性2, 属性值2, ...),其中,属性用于设置图形窗口的特征。
- 句柄变量=figure,按MATLAB默认的属性值建立图形窗口。
- figure(窗口句柄),设定该句柄对应的窗口为当前窗口。
3.2 图形窗口属性
- MenuBar属性:控制图形窗口是否具有菜单条,其取值为'none'或'figure'。
- Name属性:指定图形窗口的标题。
- NumberTitle属性:决定着在图形窗口的标题中是否以“Figure n:”为标题前缀。取值为'on'或者'off'。
- Color属性:设定图形窗口背景的颜色。
- 其他属性查看帮助文档。
例3:建立一个图形窗口。该图形窗口没有菜单条,标题名称为“图形窗口示例”。图形窗口对象起始于屏幕左下角(1,1)处,宽度和高度分别是300像素点和200像素点。背景颜色为青色。当用户从键盘按下任意一个键时,然后在窗口中单击鼠标左键,在鼠标指针所在的位置将显示“Hello World!”。
hf = figure; % 建立一个图形窗口
hf.Color = 'cyan'; % 设置背景颜色为青色
hf.Position = [1, 1, 300, 200];
hf.Name = '图形窗口示例';
hf.NumberTitle = 'on'; % 以Figure n:为图形窗口的标题前缀
hf.MenuBar = 'none'; % 图形窗口无菜单条
hf.ButtonDownFcn = 'gtext(''Hello World!'')';
4. 坐标轴对象的操作
4.1 建立坐标轴对象
使用axes函数,其调用格式是:
- 句柄变量=axes(属性1,属性值1,属性2,属性值2,…),其中,属性用于设置坐标轴的外观和行为。
- 句柄变量=axes,按MATLAB默认的属性值在当前图形窗口创建坐标轴。
- axes(坐标轴句柄),设定该句柄代表的坐标轴为当前坐标轴。
4.2 坐标轴对象的属性
- Position属性:定义坐标轴在图形窗口中的位置和大小。
- Units属性:定义坐标轴使用的度量单位,默认值是'normalized'。
- Box属性:决定坐标轴是否带有边框,可取值是'on'或'off',默认值为'off'。
- GridLineStyle属性:用于定义网格线的类型,可取值是':','-','-.','--','none',默认值是':'。
- Title属性:用于对坐标轴标题对象进行操作,取值是通过title函数建立的标题对象的句柄。
- XLabel, YLabel, ZLabel属性:取值分别是通过xlabel, ylabel, zlabel函数建立的标签对象的句柄。
- XLim, YLim, ZLim属性:分别定义各坐标轴的下限和上限,取值是2元向量[Lmin, Lmax],默认值是[0,1]。
- XScale, YScale, ZScale属性:定义各坐标轴的刻度类型。可取值是'linear','log'。
- View属性:定义视点。取值是2元向量[az, el],az定义视点的方位角,el定义视点的仰角。坐标轴默认视点的方位角是0°,仰角是90°。
- ColorOrder属性:用于设置多条曲线的颜色顺序,是一个n×3矩阵,矩阵的每一行用RGB三元组表示一种颜色,默认n为7(即有7种颜色)。
例4:利用坐标轴对象实现图形窗口的分割。
close all; clear; clc;
hal = axes('Position', [0.1, 0.1, 0.7, 0.7]);
contour(peaks(20));
hal.Title = title('等高线');
hal.YLabel = ylabel('南北向');
hal.XLabel = xlabel('东西向');
hal = axes('Position', [0.65, 0.7, 0.28, 0.28]);
surf(peaks(20));
ha2.View = [-30, 45];
例5:定义包含4种颜色的ColorOrder属性,绘制6条曲线。
close all; clear; clc;
x = [0, 0];
y = [0, 1];
ha = axes; % 按MATLAB默认的属性值在当前图形窗口创建坐标轴。
ha.ColorOrder = [0,0,0; 1,0,0; 0,1,0; 0,0,1]; % 定义4种颜色
hold on;
plot(x,y, x+0.5,y, x+1,y, x+1.5,y, x+2,y, x+2.5,y); % 绘制6条曲线
ha.XLim = [-0.2, 3];
ha.YLim = [-0.2, 1.2];
二 曲线与曲面对象
曲线和曲面是MATLAB中常见的图形对象。本部分介绍如何在坐标轴中建立曲线对象和曲面对象,以及如何修改这些对象的属性来调整它们的特征。
2.1 建立曲线对象
line函数的调用格式为:句柄变量=line(x, y, z, 属性1, 属性值1, 属性2, 属性值2, ...),其中,x, y, z是等长的向量或同型的矩阵,存储数据点的坐标。
2.2 曲线对象的常用属性
- Color属性:定义曲线的颜色,默认值为[0,0,0]。
- LineStyle属性:定义线型,默认值为‘-’。
- LineWidth属性:定义线宽,默认值为0.5磅。
- Marker属性:定义数据点标记符号,默认值为‘none’。
- MarkerSize属性:定义数据点标记符号的大小,默认值为6磅。
- XData、YData、ZData属性:设置3个坐标轴的数据源。
例6:利用曲线对象绘制奥运五环图案。
close all; clear; clc;
t = -0.1 : 0.1 : 2*pi; % 取-0.1开始是为了让各个圆环首尾闭合
x = cos(t);
y = sin(t);
line(x, y, 'Color', 'b');
line(x+1.2, y-1, 'Color', 'y');
line(x+2.4, y, 'Color', 'k'); % k表示黑色
line(x+3.6, y-1, 'Color', 'g');
line(x+4.8, y, 'Color', 'r');
ha = gca; % 获取当前坐标轴的句柄
for n = 1 : size(ha.Children) % ha.Children表示坐标轴对象的所有子对象句柄组成的向量
ha.Children(n).LineWidth = 5; % 逐个设置曲线的线宽
end
ha.XLim = [-2, 7];
ha.YLim = [-4, 3];
axis equal;
2.3 建立曲面对象
建立曲面对象使用surface函数,其调用格式为:句柄变量=surface(x, y, z, c, 属性1, 属性值1, 属性2, 属性值2, ...),其中,x, y, z是等长的向量或者同型的矩阵,存储数据点的坐标,与mesh、surf函数含义相同。c用于指定在不同高度下的曲面颜色。
surf函数每调用一次,就会刷新坐标轴,清空原有图形,再绘制新的图形。而surface函数生成的曲面则在已有图形上叠加显示。利用surface函数建立的曲面对象,默认视点在图形正上方,即方位角为0°,仰角为90°。
2.4 与曲面对象有关的属性
曲面对象除了有与曲线对象相同的属性以外,还有其他一些常用的属性,如:
- FaceColor属性:定义曲面网格片的颜色。可取值为:
‘flat’ | 每一个网格片用单一颜色填充。 |
'interp' | 用渐变方式填充网格片 |
'none' | 网格片无颜色 |
'texturemap' | 用Cdata属性定义的颜色填充网格片 |
RGB向量或代表颜色的字符 | - |
- EdgeColor属性:定义曲面网格线的颜色。
例7:利用曲面对象绘制立体圆环,圆环方程为:
,其中u∈[0, 2π],v∈[0, 2π]
close all; clear; clc;
r = linspace(0, 2*pi, 60);
[u,v] = meshgrid(r);
x = (8+3*cos(v)).*cos(u);
y = (8+3*cos(v)).*sin(u);
z = 3*sin(v);
axes('View', [-37.5, 30]); % 建立坐标轴对象
hs = surface(x, y, z); % 建立曲面对象
axis equal;
hs.EdgeColor = 'none'; % 网格线无颜色
hs.FaceColor = 'interp'; % 设置曲面网格片的颜色
2.5 光照处理
2.5.1 创建光源对象
light函数的调用格式为:对象句柄=linght(属性1,属性值1,属性2,属性值2,...),其中,属性指定光源的特性。
2.5.2 光源对象的属性
- Color属性:设置光的颜色,值是RGB三元数组或者代表颜色的字符,默认为白色。
- Style属性:设置光源类型,其取值为‘infinite’(默认值)或'local',分别表示无穷远光和近光。
- Position属性:指定光源位置,值是一个3元向量。
2.5.3 设置光照模式
利用lighting命令可以设置光照模式,lighting命令格式为:lighting 选项,其中,选项可取值为:
- flat(默认值):使得入射光均匀洒落在图形对象的每个面上。
- gouraud:先对顶点颜色插补,再对顶点勾画的面上颜色进行插补。
- phong:对顶点处的法线插值,再计算各个像素的反光。
- none:关闭所有光源。
例8:绘制光照处理后的圆环面并观察不同光照模式下的效果。
close all; clear; clc;
r = linspace(0, 2*pi, 60);
[u, v] = meshgrid(r);
x = (8+3*cos(v)).*cos(u);
y = (8+3*cos(v)).*sin(u);
z = 3*sin(v);
axes('Position', [0.05, 0.675, 1.0, 0.3], 'View', [-37.5, 30]);
hs1 = surface(x, y, z);
axis equal;
hs1.EdgeColor = 'none';
hs1.FaceColor = 'interp';
axes('Position', [0.05, 0.35, 1.0, 0.3], 'View', [-37.5, 30]);
hs2 = surface(x, y, z);
axis equal;
hs2.EdgeColor = 'none';
hs2.FaceColor = 'interp';
light('Position', [0, 0, 8]);
lighting flat;
axes('Position', [0.05, 0.025, 1.0, 0.3], 'View', [-37.5, 30]);
hs3 = surface(x, y, z);
axis equal;
hs3.EdgeColor = 'none';
hs3.FaceColor = 'interp';
light('Position', [0, 0, 8]);
lighting phong;
2.6 图形对象的反射特性
- SpecularStrength属性:控制对象表面镜面反射的强度,属性值取0-1之间的数,默认值为0.9。
- DiffuseStrength属性:控制对象表面漫反射的强度,属性值取0-1之间的数,默认值为0.6。
- AmbientStrength属性:确定环境光的强度,属性值取0-1之间的数,默认值为0.3。
- SpecularExponent属性:控制镜面反射指数,值大于等于1,大多设置在5-20之间,默认值为10。
- BackFaceLinghting属性:控制对象内表面和外表面的差别,取值为‘unlit’,‘lit’,‘reverselit’,默认值为‘reverselit’。
三 图形用户界面设计方法
1. 图形用户界面
图形用户界面(Graphical User Interface, GUI):用户与计算机进行信息交流的窗口。
设计图形用户界面的方法:
- 调用建立用户界面控件的函数
- 使用MATLAB提供的GUIDE工具进行可视化设计
2. 控件对象及其操作
2.1 常用控件
- 输入和输出类控件:编辑框、静态文本、列表框、滑动条等。
- 实施确认、选择操作类控件:按钮、双位按钮、单选按钮、复选框等。
2.2 建立控件对象
uicontrol函数用于建立控件对象,其调用格式为:句柄变量=uicontrol(图形窗口句柄, 属性1, 属性值1, 属性2, 属性值2, ...),其中,属性及其取值决定了控件的特征。若省略图形窗口句柄,默认在当前图形窗口建立控件对象。
2.3 控件对象的基本控制属性
控件对象除了具有图形对象的公共属性外,还具有一些特殊的控制属性,如:
- Style属性:定义控件对象的类型。例如'pushbutton'表示按钮对象,'edit'表示编辑框,等等。
- String属性:定义控件对象的说明文字。
- Tag属性:标识控件对象。
- Enable属性:控制控件对象是否可用。
- Position属性:定义控件对象在父对象上的位置和大小,其取值形式为[x, y, w, h]。
- Callback属性:其属性值是描述命令的字符串或函数句柄,当选中控件时,系统将自动执行字符串描述的命令或调用句柄所代表的的函数,实施相关操作。
例9:在图形窗口中建立三个按钮对象,当单击按钮时分别绘制正弦曲线、显示或隐藏坐标轴的网格、清除坐标轴的图形。
close all; clear; clc;
ha = axes('Units', 'pixels', 'Position', [40, 40, 360, 360]);
ptgrid = uicontrol('Style', 'pushbutton', ...
'String', '网格', 'Position', [450, 150, 60, 30], 'Callback', 'grid');
btncla = uicontrol('Style', 'pushbutton', ...
'String', '清除', 'Position', [450, 100, 60, 30], 'Callback', 'cla');
btnplot = uicontrol('Style', 'pushbutton', ...
'String', '绘图', 'Position', [450, 200, 60, 30]);
写完上述代码之后,可以生成如下效果:
此时点击“绘图”按钮是不会绘制正弦曲线的。因为此时并未给“绘图”按钮写入回调函数。回调函数定义对象怎样处理信息并响应某事件。回调函数的定义格式为:
function 函数名(source, eventdata)
...
end
其中,参数source是发生事件的源控件对象句柄,eventdata存储事件数据。例如,将上例的“绘图”按钮要实现的功能定义为回调函数plot_sin。将回调函数保存在当前文件夹下。
function plot_sin(source, callbackdata)
t = -pi : pi/20 : pi;
plot(t, sin(t));
end
设置“绘图”按钮的Callback属性值是plot_sin函数句柄。完整的代码如下:
close all; clear; clc;
ha = axes('Units', 'pixels', 'Position', [40, 40, 360, 360]);
ptgrid = uicontrol('Style', 'pushbutton', ...
'String', '网格', 'Position', [450, 150, 60, 30], 'Callback', 'grid');
btncla = uicontrol('Style', 'pushbutton', ...
'String', '清除', 'Position', [450, 100, 60, 30], 'Callback', 'cla');
btnplot = uicontrol('Style', 'pushbutton', ...
'String', '绘图', 'Position', [450, 200, 60, 30]);
btnplot.Callback = @plot_sin;
%%%%%%%%%%%% btnplot的回调函数 %%%%%%%%%%%%%%%
function plot_sin(source, callbackdata)
t = -pi : pi/20 : pi;
plot(t, sin(t));
end
程序运行之后,上例中的3个按钮可以正常操作。
3. 菜单对象及其操作
3.1 建立菜单对象
用户菜单一般包括一级菜单和二级菜单,每一级菜单又包括若干菜单项。MATLAB提供了uimenu函数用于创建、设置、修改菜单。
- 建立一级菜单项的函数调用格式为:
一级菜单项句柄 = uimenu(图形窗口句柄,属性1,属性值1,属性2,属性值2,…)
- 建立子菜单项的函数调用格式为:
子菜单项句柄=uimenu(上级菜单项句柄,属性1,属性值1,属性2,属性值2,…)
3.2 菜单属性
菜单对象除了具有Children、Parent、Tag等公共属性外,还具有其他一些特殊属性:
- Label属性:定义菜单项的名字。
- Accelerator属性:定义菜单项的快捷键。
- Checked属性:指示菜单项是否已选中。
- Enable属性:控制菜单项的可选择性。
- Separator属性:在菜单项上方添加一条分隔线。
例10:在例9的界面中添加“图形选项”菜单项,其中包括一个二级菜单项“线型”,其下又有3个子菜单项,分别为“实线”、“虚线”、“双划线”。
close all; clear; clc;
ha = axes('Units', 'pixels', 'Position', [40, 40, 360, 360]);
ptgrid = uicontrol('Style', 'pushbutton', ...
'String', '网格', 'Position', [450, 150, 60, 30], 'Callback', 'grid');
btncla = uicontrol('Style', 'pushbutton', ...
'String', '清除', 'Position', [450, 100, 60, 30], 'Callback', 'cla');
btnplot = uicontrol('Style', 'pushbutton', ...
'String', '绘图', 'Position', [450, 200, 60, 30]);
btnplot.Callback = @plot_sin;
%%%%%%%%%%% 例10添加的代码 %%%%%%%%%%%%%%%%%%%
hopt = uimenu(gcf, 'Label', '图形选项', 'Accelerator', 'L'); % hopt是一级菜单句柄
% gcf获取当前图形窗口的句柄,Label定义菜单项的名字为“图形选项”,Accelerator定义菜单项的快捷键为L
hLStyle = uimenu(hopt, 'Label', '线型', 'Tag', 'LStyle', 'Enable', 'off');
% hLStyle是子菜单项句柄,Label定义子菜单项的名字为“线型”,Tag定义标签为LStyle,Enable控制菜单项的可选择性
hL_Solid = uimenu(hLStyle, 'Label', '实线', ...
'Tag', 'Solid', 'Callback', @MLine_Type);
hL_Dotted = uimenu(hLStyle, 'Label', '虚线', ...
'Tag', 'Dotted', 'Callback', @MLine_Type);
hL_Dashed = uimenu(hLStyle, 'Label', '双划线', ...
'Tag', 'Dashed', 'Callback', @MLine_Type);
%%%%%%%%%%% 定义函数MLine_Type %%%%%%%%%%%%%%%
function MLine_Type(source, callbackdata)
hline = findobj('Type', 'line'); % findobj按照指定的属性来获取图形对象的句柄
if strcmp(source.Tag, 'Solid') == 1 % strcmp函数作用:比较字符串是否相同
hline.LineStyle = '-';
elseif strcmp(source.Tag, 'Dotted') == 1
hline.LineStyle = ':';
elseif strcmp(source.Tag, 'Dashed') == 1
hline.LineStyle = '--';
end
end
%%%%%%%%%%%% btnplot的回调函数 %%%%%%%%%%%%%%%
function plot_sin(source, callbackdata)
t = -pi : pi/20 : pi;
plot(t, sin(t));
h1 = findobj('Tag', 'LStyle');
h1.Enable = 'on';
end
程序运行后,图形界面的菜单栏将多出“图形选项”菜单项,这是菜单项“线型”处于不可选取的状态。单击“绘图”按钮绘制正弦曲线后,菜单项“线型”变为可选取状态,这是可以改变线型。
四 用户界面设计工具
GUIDE: Graphical User Interface Development Environment(图形用户界面开发环境)
4.1 图形用户界面设计窗口
4.1.1 打开GUIDE有两种方法:
- 在MATLAB命令行窗口输入guide命令。
- 在MATLAB主窗口中选择“主页”选项卡,单击工具栏的“新建”命令按钮,再选择“应用程序(APP)”下的GUIDE命令。
4.1.2 图形用户界面设计模板
设计模板有4种,如下图:
4.1.3 图形用户界面设计窗口
图形用户界面设计窗口由菜单栏、工具栏、控件选项板、界面设计区、状态栏等部分组成。如下图:
工具栏中几个按钮的作用:
- 属性检查器:用于检查/修改对象属性的工具。
- 菜单编辑器:添加自定义菜单,设置菜单项的属性。
- 对象浏览器:用于查看图形对象和展示界面的组织架构。
例11:建立一个图形用户界面,该界面包括1个坐标轴,3个静态文本,3个可编辑文本,2个按钮。还有1个按钮组,里面有两个单选按钮。
在图形用户界面设计窗口中设计的效果图(自己瞎设计颜色的)如下:
可在属性编辑器中修改控件对象的属性,修改之后,如下图:
保存之后,会生成.fig文件,同时系统会自动生成一个同名的.m文件。该.m文件保存了图形窗口的初始化函数,以及各控件对象的回调函数。
回调属性与回调函数:
1. 回调属性
- Callback属性:按钮类控件和菜单项的单击事件的默认回调属性。
- CreateFcn属性:定义创建图形对象的响应。
- DeleteFcn属性:定义取消图形对象的响应。
- ButtonDownFcn属性:定义单击鼠标键按下的响应。
- KeyPressFcn属性:定义键盘键按下的响应。
- SelectionChangeFcn属性:定义改变选项的响应。
2. 回调函数框架
function 对象标识_Callback(hObject, eventdata, handles)
其中,hObject为发生事件的源控件,eventdata为事件数据,handles保存图形界面中所有对象的句柄。
例12:在例11的菜单栏添加1个一级菜单项“绘图选项”,而且这个菜单只有在画有曲线时才是可用的。其下有6项,前3项定义线型,后3项定义曲线颜色。
function varargout = test(varargin)
% TEST MATLAB code for test.fig
% TEST, by itself, creates a new TEST or raises the existing
% singleton*.
%
% H = TEST returns the handle to a new TEST or the handle to
% the existing singleton*.
%
% TEST('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in TEST.M with the given input arguments.
%
% TEST('Property','Value',...) creates a new TEST or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before test_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to test_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help test
% Last Modified by GUIDE v2.5 27-Jul-2018 10:34:37
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @test_OpeningFcn, ...
'gui_OutputFcn', @test_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before test is made visible.
function test_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to test (see VARARGIN)
% Choose default command line output for test
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes test wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = test_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function editfz_Callback(hObject, eventdata, handles)
% hObject handle to editfz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editfz as text
% str2double(get(hObject,'String')) returns contents of editfz as a double
% --- Executes during object creation, after setting all properties.
function editfz_CreateFcn(hObject, eventdata, handles)
% hObject handle to editfz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editpl_Callback(hObject, eventdata, handles)
% hObject handle to editpl (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editpl as text
% str2double(get(hObject,'String')) returns contents of editpl as a double
% --- Executes during object creation, after setting all properties.
function editpl_CreateFcn(hObject, eventdata, handles)
% hObject handle to editpl (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editxj_Callback(hObject, eventdata, handles)
% hObject handle to editxj (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editxj as text
% str2double(get(hObject,'String')) returns contents of editxj as a double
% --- Executes during object creation, after setting all properties.
function editxj_CreateFcn(hObject, eventdata, handles)
% hObject handle to editxj (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
A = str2double(handles.editfz.String); % 幅值
f = str2double(handles.editpl.String)/50; % 频率
theta = str2double(handles.editxj.String)/180*pi; % 相角
x = linspace(0, 2*pi, 60);
if handles.OpSin.Value == 1
y = A*sin(f*x+theta);
else
y = A*cos(f*x+theta);
end
plot(x, y);
handles.PStyle.Enable = 'on';
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
cla;
handles.PStyle.Enable = 'off';
% --------------------------------------------------------------------
function PStyle_Callback(hObject, eventdata, handles)
% hObject handle to PStyle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function Solid_Callback(hObject, eventdata, handles)
% hObject handle to Solid (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.LineStyle = '-';
handles.Solid.Checked = 'on';
handles.Dotted.Checked = 'off';
handles.Dashed.Checked = 'off';
% --------------------------------------------------------------------
function Dotted_Callback(hObject, eventdata, handles)
% hObject handle to Dotted (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.LineStyle = ':';
handles.Solid.Checked = 'off';
handles.Dotted.Checked = 'on';
handles.Dashed.Checked = 'off';
% --------------------------------------------------------------------
function Dashed_Callback(hObject, eventdata, handles)
% hObject handle to Dashed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.LineStyle = '--';
handles.Solid.Checked = 'off';
handles.Dotted.Checked = 'off';
handles.Dashed.Checked = 'on';
% --------------------------------------------------------------------
function r_Callback(hObject, eventdata, handles)
% hObject handle to r (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.Color = 'r';
handles.r.Checked = 'on';
handles.g.Checked = 'off';
handles.b.Checked = 'off';
% --------------------------------------------------------------------
function g_Callback(hObject, eventdata, handles)
% hObject handle to g (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.Color = 'g';
handles.r.Checked = 'off';
handles.g.Checked = 'on';
handles.b.Checked = 'off';
% --------------------------------------------------------------------
function b_Callback(hObject, eventdata, handles)
% hObject handle to b (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hline = findobj('Type', 'line');
hline.Color = 'b';
handles.r.Checked = 'off';
handles.g.Checked = 'off';
handles.b.Checked = 'on';
五 APP设计工具
这里的APP是指具有图形用户界面的MATLAB程序。APP Designer是一个可视化的集成开发环境,提供了仪表、旋钮等组件,采用面向对象的设计方法。利用APP Designer可以快速开发出应用程序。
5.1 打开APP Designer
- 在MATLAB命令行窗口输入appdesigner命令。
- 在MATLAB主窗口中选择“主页”选项卡,单击工具栏“新建”命令按钮,再选择“应用程序”下的“APP Designer”命令。
5.2 APP Designer窗口
APP Designer窗口由3个部分组成,分别是:快速访问工具栏、功能区、APP编辑器。
5.3 APP编辑器
- 设计视图:用于编辑用户界面。
- 代码视图:用于编辑、调试、分析代码。
例13:建立一个APP用户界面,该界面包括1个坐标轴,2个旋钮,2个按钮和1个按钮组。
步骤1:打开APP设计器窗口,添加组件
步骤2:利用属性面板设置组件对象的属性
步骤3:定义回调函数。在定义回调函数之前,需要补充以下内容:
APP程序采用面向对象设计模式,声明对象、定义函数、设置属性和共享数据都封装在一个类中,一个MATLAB文件就是一个类的定义。
(1) 类的基本结构
- properties段:属性的定义,主要包含属性声明代码。
- methods段:方法的定义,由若干函数组成。回调函数只有一个参数app,为界面句柄,存储了界面中各个成员的数据。
classdef 类名 < matlab.apps.AppBase
properties (Access = public)
...
end
methods (Access = private)
function 函数1(app)
...
end
function 函数2(app)
...
end
end
end
(2) 访问权限
存取数据和调用函数称为访问对象成员。
- public:可用于与App的其他类共享数据。
- private:只允许在本类中访问。以下属性和函数的默认访问权限为private:属性的声明、界面的启动函数startupFcn、建立界面组件的函数createComponents、回调函数。
步骤4:将APP程序打包,打包安装之后可以在MATLAB主窗口中APP主页下直接使用该APP程序。
单击App Designer窗口的“设计器”选项卡工具栏中的“App打包”按钮,弹出“应用程序打包”对话框。
回到例13中:实现界面的绘图功能。单击“绘图”按钮,以“倍频”旋钮的值和“相角”旋钮的值为三角函数的参数绘制曲线。单击“清空”按钮,清除坐标轴中的图形。
classdef AppDomo < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
UIAxes matlab.ui.control.UIAxes
Label matlab.ui.control.Label
Knob matlab.ui.control.Knob
ButtonGroup matlab.ui.container.ButtonGroup
sinxButton matlab.ui.control.ToggleButton
cosxButton matlab.ui.control.ToggleButton
Button_2 matlab.ui.control.Button
Button_3 matlab.ui.control.Button
Knob_2Label matlab.ui.control.Label
Knob_2 matlab.ui.control.DiscreteKnob
end
methods (Access = private)
% Button pushed function: Button_2
function Button_2Pushed(app, event)
f = str2double(app.Knob_2.Value);
theta = app.Knob.Value/180*pi;
x = linspace(0, 2*pi, 60);
if app.sinxButton.Value == 1
y = sin(f*x + theta);
else
y = cos(f*x + theta);
end
% plot函数的第1个参数必须是坐标轴对象句柄
% plot函数默认的线宽是1,APP程序的线宽必须小于0.4
plot(app.UIAxes, x, y, 'LineWidth', 0.2);
end
% Button pushed function: Button_3
function Button_3Pushed(app, event)
cla(app.UIAxes);
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = 'UI Figure';
% Create UIAxes
app.UIAxes = uiaxes(app.UIFigure);
title(app.UIAxes, '显示区')
xlabel(app.UIAxes, 'X')
ylabel(app.UIAxes, 'Y')
app.UIAxes.Box = 'on';
app.UIAxes.Position = [61 239 300 185];
% Create Label
app.Label = uilabel(app.UIFigure);
app.Label.HorizontalAlignment = 'center';
app.Label.Position = [454 265 29 15];
app.Label.Text = '相角';
% Create Knob
app.Knob = uiknob(app.UIFigure, 'continuous');
app.Knob.Limits = [0 360];
app.Knob.Position = [438 314 60 60];
% Create ButtonGroup
app.ButtonGroup = uibuttongroup(app.UIFigure);
app.ButtonGroup.Title = '图形函数';
app.ButtonGroup.Position = [106 108 123 83];
% Create sinxButton
app.sinxButton = uitogglebutton(app.ButtonGroup);
app.sinxButton.Text = 'sin(x)';
app.sinxButton.Position = [11 30 100 22];
app.sinxButton.Value = true;
% Create cosxButton
app.cosxButton = uitogglebutton(app.ButtonGroup);
app.cosxButton.Text = 'cos(x)';
app.cosxButton.Position = [11 9 100 22];
% Create Button_2
app.Button_2 = uibutton(app.UIFigure, 'push');
app.Button_2.ButtonPushedFcn = createCallbackFcn(app, @Button_2Pushed, true);
app.Button_2.Position = [271 169 100 22];
app.Button_2.Text = '绘图';
% Create Button_3
app.Button_3 = uibutton(app.UIFigure, 'push');
app.Button_3.ButtonPushedFcn = createCallbackFcn(app, @Button_3Pushed, true);
app.Button_3.Position = [271 117 100 22];
app.Button_3.Text = '清空';
% Create Knob_2Label
app.Knob_2Label = uilabel(app.UIFigure);
app.Knob_2Label.HorizontalAlignment = 'center';
app.Knob_2Label.Position = [456 117 29 15];
app.Knob_2Label.Text = '倍频';
% Create Knob_2
app.Knob_2 = uiknob(app.UIFigure, 'discrete');
app.Knob_2.Items = {'0', '1', '2', '3'};
app.Knob_2.Position = [439 147 60 60];
app.Knob_2.Value = '0';
end
end
methods (Access = public)
% Construct app
function app = AppDomo
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end
六 图形用户界面应用举例
本节介绍一个GUIDE设计实例。
例14:利用GUIDE设计工具设计如图所示的用户界面。该界面可以显示表面图、网格图、等高线图。绘制图形的功能通过3个命令按钮来实现,绘制图形所需要的数据通过一个列表来选取。方位角和仰角在视点面板中设置,图形使用的色图通过下拉列表进行选择,着色方式通过单选按钮组进行选择。切换按钮用于隐藏或显示坐标轴网格。
步骤1:打开图形用户界面设计窗口,添加有关图形对象,并保存图形用户界面。
步骤2:利用属性检查器设置界面对象的属性。
- String属性:用于指定控件上的文本以及列表框和弹出式菜单的选项。弹出式菜单的选项间使用Enter作为分隔符。
- Tag属性:定义控件标识。
- Value属性:设置控件的值。
本例中按下图方式设置界面对象的属性:(图中静态文本1和静态文本2的String属性分别输入仰角和方位角)
设置好之后如下图所示:
步骤3:利用对齐对象工具,调整控件对象的相对位置。
步骤4:编写代码,实现控件功能。
(1) .m文件中回调函数的框架
控件Tag_Call类型(hObject, eventdata, handles)
其中,hObject是发生事件的源控件,eventdata是事件数据,handles是对象句柄集。
(2) 跟图形窗口有关的3个函数:
- _OpeningFcn函数:可以在这个函数内完成数据初始化设置、GUI界面的控制和调整等工作。
- _OutputFcn函数:用于控制输出运行结果。
- _Callback函数:用于控制窗口的默认事件,即单击窗口空白区域的触发行为。
(3) 为图形窗口的打开事件编写响应代码。代码写在_OpeningFcn函数中。
(4) 为3个绘图按钮编写响应代码。
(5) 为切换按钮编写响应代码。
(6) 为列表框编写响应代码。
(7) 为色图弹出式菜单编写响应代码。
(8) 为视点设置按钮编写响应代码。
(9) 为着色方式按钮组ChooseShading的SelectionChanged事件编写响应代码。
(10) 运行图形用户界面。
完整效果如下,各功能可用:
代码如下:
function varargout = GUIDemo(varargin)
% GUIDEMO MATLAB code for GUIDemo.fig
% GUIDEMO, by itself, creates a new GUIDEMO or raises the existing
% singleton*.
%
% H = GUIDEMO returns the handle to a new GUIDEMO or the handle to
% the existing singleton*.
%
% GUIDEMO('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUIDEMO.M with the given input arguments.
%
% GUIDEMO('Property','Value',...) creates a new GUIDEMO or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUIDemo_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUIDemo_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUIDemo
% Last Modified by GUIDE v2.5 06-Aug-2018 10:15:31
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @GUIDemo_OpeningFcn, ...
'gui_OutputFcn', @GUIDemo_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before GUIDemo is made visible.
function GUIDemo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to GUIDemo (see VARARGIN)
handles.peaks = peaks(34);
handles.membrane = membrane;
[x, y] = meshgrid(-8:0.3:8);
r = sqrt(x.^2+y.^2);
sinc = sin(r)./(r+eps);
handles.sinc = sinc;
handles.current_data = handles.sinc;
colormap(spring);
grid on;
% Choose default command line output for GUIDemo
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUIDemo wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = GUIDemo_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in Mesh.
function Mesh_Callback(hObject, eventdata, handles)
% hObject handle to Mesh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mesh(handles.current_data);
handles.GridSwitch.String = '隐藏网格';
handles.GridSwitch.Value = 1;
% --- Executes on button press in Surf.
function Surf_Callback(hObject, eventdata, handles)
% hObject handle to Surf (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
surf(handles.current_data);
handles.GridSwitch.String = '隐藏网格';
handles.GridSwitch.Value = 1;
% --- Executes on button press in Contour3.
function Contour3_Callback(hObject, eventdata, handles)
% hObject handle to Contour3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
contour3(handles.current_data);
handles.GridSwitch.String = '隐藏网格';
handles.GridSwitch.Value = 1;
% --- Executes on selection change in ChooseFun.
function ChooseFun_Callback(hObject, eventdata, handles)
% hObject handle to ChooseFun (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
str = hObject.String;
val = hObject.Value;
switch strtrim(str{val}) % strtrim函数用于去除字符串的首尾空格
case 'Peaks'
handles.current_data = handles.peaks;
case 'Membrane'
handles.current_data = handles.membrane;
case 'Sinc'
handles.current_data = handles.sinc;
end
guidata(hObject, handles); % guidata函数用于保存和更新数据
% Hints: contents = cellstr(get(hObject,'String')) returns ChooseFun contents as cell array
% contents{get(hObject,'Value')} returns selected item from ChooseFun
% --- Executes during object creation, after setting all properties.
function ChooseFun_CreateFcn(hObject, eventdata, handles)
% hObject handle to ChooseFun (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in ChooseCMap.
function ChooseCMap_Callback(hObject, eventdata, handles)
% hObject handle to ChooseCMap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
str = hObject.String;
cm = hObject.Value;
colormap(eval(str{cm}));
% Hints: contents = cellstr(get(hObject,'String')) returns ChooseCMap contents as cell array
% contents{get(hObject,'Value')} returns selected item from ChooseCMap
% --- Executes during object creation, after setting all properties.
function ChooseCMap_CreateFcn(hObject, eventdata, handles)
% hObject handle to ChooseCMap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in GridSwitch.
function GridSwitch_Callback(hObject, eventdata, handles)
% hObject handle to GridSwitch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if hObject.Value == 1
grid on;
hObject.String = '隐藏网格';
else
grid off;
hObject.String = '显示网格';
end
% Hint: get(hObject,'Value') returns toggle state of GridSwitch
function edit_el_Callback(hObject, eventdata, handles)
% hObject handle to edit_el (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_el as text
% str2double(get(hObject,'String')) returns contents of edit_el as a double
% --- Executes during object creation, after setting all properties.
function edit_el_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_el (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_az_Callback(hObject, eventdata, handles)
% hObject handle to edit_az (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_az as text
% str2double(get(hObject,'String')) returns contents of edit_az as a double
% --- Executes during object creation, after setting all properties.
function edit_az_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_az (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in ConfigView.
function ConfigView_Callback(hObject, eventdata, handles)
% hObject handle to ConfigView (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
el = str2double(handles.edit_el.String);
az = str2double(handles.edit_az.String);
view(az, el);
% Hint: get(hObject,'Value') returns toggle state of ConfigView
% --- Executes on button press in clear.
function clear_Callback(hObject, eventdata, handles)
% hObject handle to clear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1);
cla reset;
grid on;
handles.GridSwitch.String = '隐藏网格';
handles.GridSwitch.Value = 1;
% --- Executes when selected object is changed in ChooseShading.
function ChooseShading_SelectionChangedFcn(hObject, eventdata, handles)
% hObject handle to the selected object in ChooseShading
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
switch eventdata.NewValue.Tag % 按钮组中的控件标签
case 'flat'
shading flat;
case 'interp'
shading interp;
case 'faceted'
shading faceted;
end