Skip to content

Instantly share code, notes, and snippets.

@junaidk
Created November 27, 2013 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junaidk/7674306 to your computer and use it in GitHub Desktop.
Save junaidk/7674306 to your computer and use it in GitHub Desktop.
Matlab dragNdrop
%% define each of these functions in separate function files
%% with file name equal to function name
%1
function dropObject(hObject,eventdata)
global dragging ;
global orPos ;
global axisSize;
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
posDiff = posDiff.*axisSize;
%set(dragging,'Position',get(dragging,'Position') + [posDiff(1:2) 0 0]);
set(dragging,'Xdata',get(dragging,'Xdata')+[posDiff(1) posDiff(1)], ...
'Ydata',get(dragging,'Ydata')+[posDiff(2) posDiff(2)]);
dragging = [];
end
end
%2
function moveObject(hObject,eventdata)
global dragging ;
global orPos ;
global axisSize;
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
orPos = newPos;
posDiff = posDiff.*axisSize;
%set(dragging,'Position',get(dragging,'Position') + [posDiff(1:2) 0 0]);
set(dragging,'Xdata',get(dragging,'Xdata')+[posDiff(1) posDiff(1)], ...
'Ydata',get(dragging,'Ydata')+[posDiff(2) posDiff(2)]);
end
end
%3
function dragObject(hObject,eventdata)
global dragging;
global orPos;
dragging = hObject;
orPos = get(gcf,'CurrentPoint');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% initilaize main file like this
f = figure('WindowButtonUpFcn',@dropObject,'units','normalized','WindowButtonMotionFcn',@moveObject);
global dragging ;
global orPos ;
global axisSize;
axisSize = 1500;
axis([0 axisSize 0 axisSize])
hold on
%% add this property to image you want to drag
ximg = imread('city.png');
h_img = image(ximg,'ButtonDownFcn',@dragObject);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment