The following code creates a ruler (imdistline) and defines a callback function on position change, so I can have a label move as the ruler moves. Problem is the callback seems to lose the new handles, so every call to redraw the label doesn't find an existing label and draws another at the new position. Relevant code is as follows:
% --- Executes on button press in rulerPushButton.
function rulerPushButton_Callback(hObject, ~, handles) % Create a ruler on the zoomAxes
% if ruler doesn't exist, create one
if ~isfield(handles.ruler, 'handle') % TODO check if this works for destroyed handle
handles.ruler.handle = imdistline(handles.zoomAxes); handles.ruler.api = iptgetapi(handles.ruler.handle); setColor(handles.ruler.api, [1 1 0]); drawRulerLabels(hObject, handles); % Constrain ruler to image boundaries
constrainToRectFcn = makeConstrainToRectFcn('imline', get(handles.zoomAxes, 'XLim'), get(handles.zoomAxes,'YLim')); handles.ruler.api.setPositionConstraintFcn(constrainToRectFcn); % Create callback for ruler movement
% Create anonymous function to pass as callback
% anonfnc = function handle name
% @ creates handle
% (x) input arguments
% followed by statement
anonCB = @(pos) rulerNewPos_Callback(hObject, handles, pos); handles.ruler.api.addNewPositionCallback(anonCB); guidata(hObject, handles); end end% Executes on ruler movement. pos is 2-by-2 array [x1 y1; x2 y2]
function rulerNewPos_Callback(hObject, handles, ~) handles = drawRulerLabels(hObject, handles); guidata(hObject, handles); % Doesn't work
end
handles = drawRulerLabels(hObject, handles) does what it should and returns correct handles, but after guidata(hObject, handles) and returning from the function the handles are lost. I'm assuming it's because the passed hObject is incorrect but I'm not sure why that should be. You can probably tell by the comments I'm not too familiar with anonymous functions and I suspect the problem could be in there somewhere. Any help appreciated.
Best Answer