问题描述
大家好,我想知道如何为 GUI 静态文本框上的特定值分配颜色。下面是我用来为静态文本框赋值的编码。但我不知道如何为值分配颜色。例如a=50,静态文本框的颜色变为绿色。当 a=60 时,静态文本框的颜色变为黄色。提前致谢。
set(ah,'handlevisibility','off','visible','off')
d= 500;
t= 10;
a= [num2str(d/t) 'km/h'];
set(handles.Speed,'String',a);
解决方法
我创建了一个函数,其中输入 d
和 t
,然后它将生成文本框的背景颜色根据速度 (d/t) 变化的图形。为了将速度转换为颜色,我设置了一个 color_matrix
变量,它的第一列是速度,接下来的 3 列是指定颜色所需的红色、绿色和蓝色值。您可以添加更多行以包含更多颜色,例如从红色到黄色再到绿色。
function ShowSpeed(d,t)
figure(1)
clf
ah = uicontrol('style','text','units','normalized','Position',[0.5,0.5,0.3,0.1],'FontSize',12);
velocity = d / t;
a = [num2str(velocity) 'km/h'];
% first column is the velocity,2-4 columns are the red,green,blue values respectively
color_matrix = [50,0; ... % dark breen for 50
60,1,.07]; % yellow for 60
background_color = interp1(color_matrix(:,1),color_matrix(:,2:4),velocity,'linear','extrap');
% make sure color values are not lower than 0
background_color = max([background_color; 0,0]);
% make sure color values are not higher than 1
background_color = min([background_color; 1,1]);
set(ah,'String',a,'BackgroundColor',background_color);
这是速度为 50 的结果:
ShowSpeed(500,10)
这是速度为 60 时的结果
ShowSpeed(600,10)
您也可以进行内插和外推,但不能走得太远。