本文共 2693 字,大约阅读时间需要 8 分钟。
(版本:MATLAB2015b)
使用waitforbuttonpress ,该函数会根据用户的下一步操作返回一个值,具体如下:
return 0 if it detects a mouse button click %鼠标点击;
return 1 if it detects a key press %键盘键入; 用这个功能结合CurrentPoint可以实现在matlab中作图时循环持续返回点击的位置的信息以及通过键盘键入任意键来退出程序,十分方便。
t = 0:pi/36:2*pi;x = cos(t)*10;y = sin(t)*6;figure(1);ell = plot(x,y); %以绘制一个椭圆为例;grid on;set(ell,'LineWidth',3);k = waitforbuttonpress; %获取第一个操作while(k == 0) pt = get(gca,'CurrentPoint'); %获取最近一次鼠标点击的位置信息,返回一个2*3的struct; x = pt(1,1); y = pt(1,2);%这里没有用到z坐标的值; fprintf('The position is ( %.3f , %.3f )\n',x,y); %我们保留三位小数; k = waitforbuttonpress; %再次获取鼠标或键盘的键入指令; if(k == 1) disp('Exit!'); %如果是键盘输入, break; %则直接跳出循环,结束程序; endend %否则循环等待获取新的鼠标点击信息;close all; %关闭图像;
下面再展示一个结合CurrentPoint 和CurrentCharacter使用的例子,
CurrentPoint:从当前坐标轴句柄(gca)返回最近一次鼠标点击的点的坐标信息;
CurrentCharacter:从当前图像句柄(gcf)返回最近一次键盘键入的一个字符的信息;
在本例中,用户可以点击图像中的任意点,命令行会输出对应的坐标信息,输入c或C可改变图像线条的颜色(提前设定好的两种颜色可重复相互交换,下同),输入w或W可以改变图像线条的宽度,输入s或S可以改变线条的类型,输入x或X可以退出程序。
t = 0:pi/36:2*pi;x = cos(t)*10;y = sin(t)*6;figure(1);ell = plot(x,y);grid on;k = 0; c = 0; s = 0; w = 0; %参数状态记录符;while(k == 0) k = waitforbuttonpress; %等待用户输入; if(k == 1) k = 0; %使得循环不被终止而是继续; Cha = get(gcf,'CurrentCharacter'); %获取最近一次键入的字符; if(strcmpi(Cha,'c')) %使用strcmpi函数比较字符,不区分大小写; if(c == 0) c = 1; set(ell,'Color','r'); else c = 0; set(ell,'Color','b'); end disp('Color changed!'); end if(strcmpi(Cha,'s')) if(s == 0) s = 1; set(ell,'LineStyle','-.'); else s = 0; set(ell,'LineStyle','default'); end disp('LineStyle changed!'); end if(strcmpi(Cha,'w')) if(w == 0) w = 1; set(ell,'LineWidth',3); else w = 0; set(ell,'LineWidth',1.5); end disp('LineWidth changed!'); end if(strcmpi(Cha,'x')) disp(' Exit!'); break; end else pt = get(gca,'CurrentPoint'); %获取鼠标点击的点的信息; x = pt(1,1); y = pt(1,2); fprintf('The position is ( %.3f , %.3f )\n',x,y); endendclose all;
注:如有错误和不当的地方,还请各路大佬批评指正!
转载地址:http://xhvrj.baihongyu.com/