Is it possible to rotate a rectangle?

조회 수: 6 (최근 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