MATLAB: How to make the slider bar change color according to its value in MATLAB 7.8 (R2009a)

changecolorMATLABshowslidervalue

I have a slider bar that shows information of the value and I want to use color to indicate how large the value is.

Best Answer

The way can be varied to use color to show the value information.
Assuming sld is the handle of an exisiting horizontal slider.
Method 1: Use backgroundcolor and callback properties, and COLORMAP to automatically generate colors
The following code involves writing a callback function to change backgrond color of the slider. Firstly generate color value matrix using COLORMAP. Then write the callback function to map the value to the color matrix index, and set the background color of the slider.
%%%BEGIN COD%%%
%Use 100 colors corresponding to the value change
bc=colormap(jet(100));
set(sld,'Callback',@changecolor);
function changecolor(hObject,eventdata)
%map default value range into 1-100
cidx=round(get(hObject,'Value')*99+1);
set(hObject, 'BackgroundColor',bc(cidx,:));
end
It is equivalent to using GUIDE to set values in the 'Callback' property of the Property Inspector.
Method 2: Use COLORBAR
Using COLORBAR adds a new axis near the slider, and can specify information related to the value.
%%%BEGIN COD%%%
colormap jet; % X value ranging 1-64
h=colorbar('Location','North');axis off;
set(h,'XTick',[1 20 40 60], 'XTickLabel',{'Low','Normal','Medium','High'});
bpos=get(sld,'Position');
%ColorBar is under the slider, with the same left startlength
bpos(2)=pos(2)-30;
bpos(4)=20;
set(h,'Units','pixels','Position',bpos);