大家好我想在matlab中编写一个程序,在gui中显示一个矩形并使其闪烁。闪烁的速度定义为period = 1 / freq
这很简单,但我不知道为什么它不能正常工作。
想要做的是使该矩形显示并消失为指定的频率
这是我的代码,它没有显示任何错误
figure
% the flashing block on frequency
t = timer;
set(t, 'executionMode', 'fixedRate');
freq = 10;
period = 1/freq;
set(t, 'Period', 1/freq);
set(t, 'TimerFcn', 'show');
flash = true;
show = rectangle('Position',[0,0,1,1],'FaceColor','w');
hide = rectangle('Position',[0,0,1,1],'FaceColor','black');
while (true);
% set the background to black
set (gcf, 'Color', [0 0 0] );
% drawing the rect box
n = plot(show);
wait = period;
m = plot(hide);
set(gca,'xcolor',get(gcf,'color'));
set(gca,'ycolor',get(gcf,'color'));
set(gca,'ytick',[]);
set(gca,'xtick',[]);
return
end
我不知道为什么它不起作用。有人可以向我解释
答案 0 :(得分:1)
当您使用n = plot(show)
或m = plot(hide)
时,您实际上是在尝试将手柄所代表的数字绘制到您创建的矩形中,因此它不会显示矩形而是显示一个点
您可以做的是在循环之前定义矩形的位置,并在每次要显示时简单地调用函数rectangle
。但是这很麻烦,因为您需要在显示新矩形之前删除每个矩形。
正如@CitizenInsane所指出的,更好的方法是在循环之前为矩形分配句柄(就像你实际做的那样)并简单地来回切换每个来回的Visible
属性;结果相同,但效率更高,更轻松。
示例:
figure
% the flashing block on frequency
t = timer;
set(t, 'executionMode', 'fixedRate');
freq = 10;
period = 1/freq;
set(t, 'Period', 1/freq);
set(t, 'TimerFcn', 'show');
flash = true;
RectPos = [0,0,1,1];
%// Set the visible property to off.
show = rectangle('Position',RectPos,'FaceColor','w','Visible','off');
hide = rectangle('Position',RectPos,'FaceColor','k','Visible','off');
% set the background to black
set (gcf, 'Color', [0 0 0] );
while true;
%// Play with the "Visible" property to show/hide the rectangles.
set(show,'Visible','on')
pause(period)
set(show,'Visible','off')
set(hide,'Visible','on');
drawnow
pause(period)
set(hide,'Visible','off');
set(gca,'xcolor',get(gcf,'color'));
set(gca,'ycolor',get(gcf,'color'));
set(gca,'ytick',[]);
set(gca,'xtick',[]);
end
希望有所帮助!