How to save in a drag and drop

5 次查看(过去 30 天)
axel rose
axel rose 2020-12-26
回答: Jan 2020-12-30
function drag_drop
dragging = [];
orPos = [];
f = figure('WindowButtonUpFcn',@dropObject,'units','normalized','WindowButtonMotionFcn',@moveObject);
tmp = text(0.35,0.35,'Room','VerticalAlignment','bottom');
a = rectangle('position',[0.35, 0.35, 0.35, 0.35],'FaceColor','w','ButtonDownFcn',@dragObject,'UserData',tmp);
tmp = text(0.1,0.1,'StudyTable','VerticalAlignment','bottom');
b = rectangle('position',[0.1, 0.1, 0.1, 0.1],'FaceColor','y','ButtonDownFcn',@dragObject,'UserData',tmp);
tmp = text(0.1,0.1,'CoffeeTable','VerticalAlignment','bottom');
c = rectangle('position',[0.1, 0.1, 0.1, 0.1],'FaceColor','y','ButtonDownFcn',@dragObject,'UserData',tmp);
set(gca,'XLim',[0,1],'YLim',[0,1])
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;
rectpos = get(dragging,'Position') + [posDiff(1:2) 0 0];
set(dragging,'Position',rectpos);
set(dragging.UserData,'Position',rectpos(1:3));
dragging = [];
end
end
function moveObject(hObject,eventdata)
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
orPos = newPos;
rectpos = get(dragging,'Position') + [posDiff(1:2) 0 0];
set(dragging,'Position',rectpos);
set(dragging.UserData,'Position',rectpos(1:3));
end
end
end
The code above is a drag and drop. Im able to move the items around in the space but i cannot save it. Therefore, if i run it again, the items will go back to their original positions regardless of what position i dragged it to . How do i make the drag and drop savable so that when i run it again it will go back to how i previously left the items in matlab.

回答(1 个)

Jan
Jan 2020-12-30
There are some problems with the movement: The object does not move exactly as the mouse.
But you are asking for saving the positions. You can either save the figure by the savefig command. Or create an own save function, which store the positions of the objects. Then loading the file does restore the positions instead of creating new objects.
function drag_drop(Command)
switch Commad
case 'create'
... your code comes here
case 'save'
savefig(f, fullfile(tempdir, 'myDragDropFigure.fig'));
delete(f);
case 'load'
f = openfig(fullfile(tempdir, 'myDragDropFigure.fig'));
end

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by