How to save in a drag and drop

조회 수: 6 (최근 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에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by