Drag and Drop UIComponents with specific Regions?

1 次查看(过去 30 天)
Using the function from the following link, How do I implement Drag and Drop functionality in MATLAB?, (also shown below), I have a single button on top of an Axes object, on top of a Figure. I have attached a Dummy version of the code I am working on (I cannot share the complete file, but this is stripped and complete enough to handle the question.
I am trying to make it so that the button cannot move past the bounds given by the axes, which is easily done, I would imagine, but I am lost.
I have been working in the moveObject function, because I am assuming this is where I will put the if structure to handle the constraints.
The end goal is to allow the button to be moved ONLY within the specified region (the Axes object), regardless of if the user tries to drag the button outside of the region.
Attached is DummyButton.m, which should run on Matlab 2016b, or later. I am currently using a String Object. Thanks a million for the help, and the insight on this matter.
function drag_drop
dragging = [];
orPos = [];
f = figure('WindowButtonUpFcn',@dropObject,'units','normalized','WindowButtonMotionFcn',@moveObject);
a = annotation('textbox','position',[0.2 0.2 0.2 0.2],'String','Hello','ButtonDownFcn',@dragObject);
function dragObject(hObject,eventdata)
dragging = hObject;
orPos = get(gcf,'CurrentPoint');
end
function dropObject(hObject,eventdata)
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
set(dragging,'Position',get(dragging,'Position') + [posDiff(1:2) 0 0]);
dragging = [];
end
end
function moveObject(hObject,eventdata)
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
orPos = newPos;
set(dragging,'Position',get(dragging,'Position') + [posDiff(1:2) 0 0]);
end
end
end

回答(1 个)

Rishi Binda
Rishi Binda 2018-9-4
编辑:Rishi Binda 2018-9-4
You have to work with dropObject function alongwith moveObject as you want the figure to stay within the boundaries after releasing mouse button.
pos = get(dragging,'Position') + [posDiff(1:2) 0 0]
Apply boundary constraints on pos using if statements. Set it to boundary values if it is outside the figure window.

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by