Main Content

自动刷新使用 GUIDE 创建的 App 中的绘图

注意

在以后的版本中将会删除 GUIDE 环境。在删除 GUIDE 后,使用 GUIDE 创建的现有 App 可以继续在 MATLAB® 中运行,但不能在 GUIDE 中对其进行编辑。

要继续编辑使用 GUIDE 创建的现有 App,请参阅 GUIDE 迁移策略,了解有关如何帮助保持该 App 与未来 MATLAB 版本的兼容性的信息。要以交互方式创建新 App,请改用使用 App 设计工具开发 App

此示例说明如何查看和运行一个预置的使用 GUIDE 创建的 App。该 App 将会显示一幅曲面图,在曲面图中添加随机干扰,并按固定的时间间隔刷新绘图。该 App 包含两个按钮:一个用于开始在绘图中添加随机干扰,另一个用于停止添加干扰。用户可以使用绘图下面的滑块,将刷新周期设为 0.01 到 2 秒之间。

打开并运行示例

打开并运行 App。移动滑块,将刷新时间间隔设为 0.01 到 2.0 秒之间的值。然后点击 Start Randomizing 按钮,开始在绘制的函数中添加随机干扰。点击 Stop Randomizing 按钮,停止添加干扰和刷新绘图。

查看代码

  1. 在 GUIDE 中,点击编辑器按钮 以查看代码。

  2. 在编辑器窗口靠近顶部的位置,使用 转至 按钮导航到下面讨论的函数。

ex_guide_timergui_OpeningFcn

ex_guide_timergui_OpeningFcn 函数在 App 打开并开始运行时执行。此命令会创建 timer 对象,并将其存储在 handles 结构体中。

handles.timer = timer(...
    'ExecutionMode', 'fixedRate', ...       % Run timer repeatedly.
    'Period', 1, ...                        % Initial period is 1 sec.
    'TimerFcn', {@update_display,hObject}); % Specify callback function.
计时器的回调函数为 update_display,该函数被定义为局部函数。

update_display

update_display 函数在指定的 timer 周期已过时执行。该函数获取 Surface 对象的 ZData 属性中的值,并在其中添加随机干扰。然后它会更新绘图。

handles = guidata(hfigure);
Z = get(handles.surf,'ZData');
Z = Z + 0.1*randn(size(Z));
set(handles.surf,'ZData',Z);

periodsldr_Callback

periodsldr_Callback 函数在用户移动滑块时执行。它通过获取滑块值并将其截断来计算计时器周期。然后,它会更新滑块下面的标签,并更新 timer 对象的周期。

% Read the slider value
period = get(handles.periodsldr,'Value');
% Truncate the value returned by the slider.
period = period - mod(period,.01);
% Set slider readout to show its value.
set(handles.slidervalue,'String',num2str(period))
% If timer is on, stop it, reset the period, and start it again.
if strcmp(get(handles.timer, 'Running'), 'on')
    stop(handles.timer);
    set(handles.timer,'Period',period)
    start(handles.timer)
else               % If timer is stopped, reset its period.
    set(handles.timer,'Period',period)
end

startbtn_Callback

如果计时器尚未运行,则 startbtn_Callback 函数将会调用 timer 对象的 start 方法。

if strcmp(get(handles.timer, 'Running'), 'off')
    start(handles.timer);
end

stopbtn_Callback

如果计时器当前正在运行,则 stopbtn_Callback 函数将会调用 timer 对象的 stop 方法。

if strcmp(get(handles.timer, 'Running'), 'on')
    stop(handles.timer);
end

figure1_CloseRequestFcn

figure1_CloseRequestFcn 回调在用户关闭 App 时执行。如果 timer 对象正在运行,该函数将停止并删除 timer 对象,然后删除图窗窗口。

if strcmp(get(handles.timer, 'Running'), 'on')
    stop(handles.timer);
end
% Destroy timer
delete(handles.timer)
% Destroy figure
delete(hObject);

相关主题