Hey Axel,
I understand you want to rotate rectangles you plotted on your interactive figure for a floor planner you were trying to develop. As far as my knowledge 'rectangle' function does not support rotation. But the workaround is to use 'patch' or 'hgtransform'.
To achieve this using 'patches' in the following approach we can make the following changes:
- Replaced 'rectangle' with 'patch'
- Added rotation with 'r' key using rotation matrices
Below is the code with the changes.
function drag_drop
dragging = [];
orPos = [];
selected = [];
f = figure('WindowButtonUpFcn', @dropObject, ...
'WindowButtonMotionFcn', @moveObject, ...
'KeyPressFcn', @rotateObject, ...
'units', 'normalized');
axis([0 1 0 1]);
axis manual;
% Create three draggable & rotatable patches
createObject([0.35, 0.35], [0.35, 0.35], 'Room', 'w');
createObject([0.1, 0.1], [0.1, 0.1], 'StudyTable', 'y');
createObject([0.25, 0.1], [0.1, 0.1], 'CoffeeTable', 'y');
function createObject(pos, size, label, color)
x = pos(1); y = pos(2); w = size(1); h = size(2);
verts = [x y;
x+w y;
x+w y+h;
x y+h];
p = patch('XData', verts(:,1), 'YData', verts(:,2), ...
'FaceColor', color, 'ButtonDownFcn', @dragObject);
txt = text(x + w/2, y + h/2, label, ...
'HorizontalAlignment', 'center', ...
'VerticalAlignment', 'middle');
% Store original data
p.UserData = struct('Text', txt, ...
'Rotation', 0, ...
'Center', [x + w/2, y + h/2]);
end
function dragObject(hObject, ~)
dragging = hObject;
selected = hObject;
orPos = get(gca, 'CurrentPoint');
end
function dropObject(~, ~)
dragging = [];
end
function moveObject(~, ~)
if isempty(dragging), return; end
newPos = get(gca, 'CurrentPoint');
diff = newPos(1,1:2) - orPos(1,1:2);
orPos = newPos;
% Move vertices
x = get(dragging, 'XData') + diff(1);
y = get(dragging, 'YData') + diff(2);
set(dragging, 'XData', x, 'YData', y);
% Move text
userData = dragging.UserData;
newCenter = userData.Center + diff;
userData.Center = newCenter;
set(userData.Text, 'Position', newCenter);
dragging.UserData = userData;
end
function rotateObject(~, event)
if isempty(selected), return; end
if strcmp(event.Key, 'r')
% Rotate 15 degrees
rotatePatch(selected, 15);
end
end
function rotatePatch(patchObj, angle)
userData = patchObj.UserData;
theta = deg2rad(angle);
R = [cos(theta), -sin(theta); sin(theta), cos(theta)];
% Rotate around center
x = get(patchObj, 'XData')'; x = x(:);
y = get(patchObj, 'YData')'; y = y(:);
vertices = [x y];
center = userData.Center;
centered = vertices - center;
rotated = (R * centered')';
newVerts = rotated + center;
% Apply new vertices
set(patchObj, 'XData', newVerts(:,1), 'YData', newVerts(:,2));
set(userData.Text, 'Position', mean(newVerts,1));
userData.Rotation = mod(userData.Rotation + angle, 360);
patchObj.UserData = userData;
end
end
Here are some MATLAB Answer link discussing rotation of rectangle:
Here is the documentation of 'patches' and 'hgtransform' for your reference: