Is it possible to rotate a rectangle?

2 次查看(过去 30 天)
Su
Su 2020-1-29
编辑: DGM 2025-6-27
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

回答(2 个)

DGM
DGM 2025-6-27
编辑:DGM 2025-6-27
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 2025-6-27
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:

类别

Help CenterFile Exchange 中查找有关 Interactions, Camera Views, and Lighting 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by