Is it possible to rotate a rectangle?

2 visualizaciones (últimos 30 días)
Su
Su el 29 de En. de 2020
Editada: DGM el 27 de Jun. de 2025
I have,
GAL_fld = [227 360 105 65];
figure
plot(ExtractedX, ExtractedY);
rectangle ('position', GAL_fld); %GAL
-However how could i rotate a rectangle in this format, because I want it at an angle

Respuestas (2)

DGM
DGM el 27 de Jun. de 2025
Editada: DGM el 27 de Jun. de 2025
The rotate() function only applies to certain types of graphics objects, and rectangle() objects are not included. You can still use hgtransform() on rectangles though. This answer includes an example:
In that answer, I also include code to generate XY vertex data that can be used directly with plot(), patch(), polyshape(), etc. In that way, you can easily create rounded rectangles which mimic those created by rectangle(), but without the limitations of using rectangle objects.

Vedant Shah
Vedant Shah el 27 de Jun. de 2025
Hi @Su,
To draw a rotated rectangle in MATLAB, the built-in rectangle function is not suitable, as it only supports axis-aligned rectangles. Instead, the rectangle can be manually constructed by calculating the coordinates of its four corners after rotation and then using the fill or patch function to render it.
Below is a sample code snippet that demonstrates this approach:
x = 227; y = 360; w = 105; h = 65;
theta = 30;
corners = [x, y; x+w, y; x+w, y+h; x, y+h]';
cx = x + w/2;
cy = y + h/2;
corners_centered = corners - [cx; cy];
R = [cosd(theta) -sind(theta); sind(theta) cosd(theta)];
rotated_corners = R * corners_centered + [cx; cy];
figure;
hold on
h = fill(rotated_corners(1,:), rotated_corners(2,:), 'r');
set(h, 'FaceColor', 'none', 'EdgeColor', 'r', 'LineWidth', 2);
axis equal
hold off
Above code calculates the corners of a rectangle based on its position and size, then rotates it around its center using a rotation matrix. After applying the transformation, it uses the fill function to draw the rotated rectangle with a red border and no fill color. This approach allows for flexible visualization of rectangles at any orientation.
For more information, refer to the following documentations:

Categorías

Más información sobre Interactions, Camera Views, and Lighting en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by