MATLAB绘制动态滚动条

function scrollbar()
%% 初始化滚动条参数
a = 50;    %滚动条左边界与窗口左边界的距离
b = 50;    %滚动条右边界与窗口右边界的距离
width = 450;  %窗口的宽度
height = 200;  %窗口的高度
strDisp = '感时花溅泪,恨别鸟惊心。';  %要滚动显示的字符串
%% 创建隐藏的窗口,并将窗口移到屏幕中间
hFigure = figure('Name', '滚动条设计实例', 'MenuBar', 'none', 'ToolBar', 'none',...
   'NumberTitle', 'off',  'Units', 'points', 'Position', [0 0 width height],...
   'Visible', 'off');
movegui(hFigure, 'center');
%% 创建滚动条边框和背景
axes('Box', 'on', 'DrawMode', 'fast', 'XTick', [], 'YTick', [], 'XTickLabel',...
    '', 'YTickLabel', '', 'XLim', [0 500], 'YLim', [0 10], 'Units', 'points',...
    'Position', [a height/2 width-a-b 30]);
%% 创建文本对象,用于滚动显示字符串。注意text对象的Clipping属性默认值为off,要设置为on
hText1 = text('String', strDisp, 'Position', [500 5], 'FontWeight', 'bold',...
     'Hor', 'left', 'vert', 'middle', 'Clipping', 'on'); %创建文本对象hText1,
hText2 = text('String', strDisp, 'Position', [-500 5], 'FontWeight', 'bold',...
    'Color', 'r', 'Hor', 'left', 'vert', 'middle', 'Clipping', 'on'); %创建文本控件hDown2
%% 显示窗口
set(hFigure, 'Visible', 'on');
%% 创建定时器对象
t = timer('Period', 0.1, 'TimerFcn', {@timeUpdate, hText1, hText2}, 'BusyMode', 'queue',...
    'ExecutionMode', 'fixedRate');
start(t); %启动定时器
end

function timeUpdate(obj, ~, hText1, hText2)
%% 循环显示
if ishandle(hText1)
    pos1 = get(hText1, 'position'); %获取第1个文本对象的位置
    pos2 = get(hText2, 'position'); %获取第2个文本对象的位置
    pos1(1) = pos1(1) - 10;       %更新第1个文本对象的位置变量
    pos2(1) = pos2(1) - 10;       %更新第2个文本对象的位置变量
    %% 若hText1对象在hText2的右边,且hText1对象左边超出坐标轴,则将hText2移到坐标轴最右边
    if pos1(1) > pos2(1) && pos1(1) < 0.2 
        pos2(1) = 500;
    elseif pos2(1) > pos1(1) && pos2(1) < 0.2
        pos1(1) = 500;
    end
    set(hText1, 'position', pos1);  %更新第1个文本对象的位置
    set(hText2, 'position', pos2);  %更新第2个文本对象的位置
else  %若关闭窗口,停止并删除定时器
    stop(obj);
    delete(obj);
    clear obj;
end
end

在这里插入图片描述
开发工具:MATLAB 2022b
微信Alt+A截屏工具
本程序摘自罗华飞的《MATLABGUI设计学习手册》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值