Rotate a Rectangle within boundaries

3 次查看(过去 30 天)
I am trying to have a red rectangle be inside the green rectangle with a random rotation. I have almost accomplished this, but the only thing that is not working is that the rotation goes out the green rectangle's bounds...
cla reset
hold on
width = 1;
P = rectangle('Position',[ 0.2 -width/2 width width],'FaceColor','green'); % Placement square
a = 0.2;
b = 1.2-0.3;
r = a + (b-a).*rand(1,1); % random for horz
a = -0.5;
b = 0.5-0.2;
r2 = a + (b-a).*rand(1,1); % random for vert
x1 = r;
x2 = r + 0.3;
y1 = r2;
y2 = r2 + 0.2;
X= [x1 x1 x2 x2];
Y= [y1 y2 y2 y1];
hSquare = fill(X,Y,'r');
thetad = 45;
% thetad = randi([0 360],1);
R = [cosd(thetad) -sind(thetad); sind(thetad) cosd(thetad)];
C = repmat([0 0], 4, 1)';
axis([-1 1 -1 1])
V = get(hSquare,'Vertices')'; % get the current set of vertices
V = R*(V - C) + C; % do the rotation relative to the centre of the square
set(hSquare,'Vertices',V'); % update the vertices
axis equal

回答(2 个)

Benjamin Thompson
Benjamin Thompson 2022-2-15
If you want the red shape to sometimes touch the boundaries of the green shape while staying entirely within the green, then you cannot have both the center of the red shape and its rotation angle entirely random. You may need to choose the rotation angle first, and then based on that choose the allowable center position of the red shape.

DGM
DGM 2022-2-15
编辑:DGM 2022-2-15
Here.
% rectangle parameters
szR1 = [1 1]; % size of large rectangle
osR1 = [0.2 -szR1(2)/2]; % offset of large rectangle
szR2 = [0.3 0.2]; % size of small rectangle
% generate random angle
thR2 = randi([0 360],1);
% build point list, rotate
R = [cosd(thR2) -sind(thR2); sind(thR2) cosd(thR2)];
XY = [-1 -1; 1 -1; 1 1; -1 1].*szR2/2;
XY = (R*XY.').';
% apply constrained random translation
randos = rand(1,2);
os0 = range(XY,1); % this is the size of the rotated block
XY = XY + (szR1-os0).*randos + osR1 + os0/2;
% plot stuff
P = rectangle('Position',[osR1 szR1],'FaceColor','green');
hold on;
hSquare = fill(XY(:,1),XY(:,2),'r');
axis equal
axis([0 2 -1 1])
Or you could draw a bunch of red blocks
figure
% rectangle parameters
szR1 = [1 1];
osR1 = [0.2 -szR1(2)/2];
szR2 = [0.3 0.2];
nblocks = 50;
% plot bg
P = rectangle('Position',[osR1 szR1],'FaceColor','green'); % Placement square
hold on;
for k = 1:nblocks
% generate random angle
thR2 = randi([0 360],1);
% build point list, rotate
R = [cosd(thR2) -sind(thR2); sind(thR2) cosd(thR2)];
XY = [-1 -1; 1 -1; 1 1; -1 1].*szR2/2;
XY = (R*XY.').';
% apply constrained random translation
randos = rand(1,2);
os0 = range(XY,1); % this is the size of the rotated block
XY = XY + (szR1-os0).*randos + osR1 + os0/2;
% plot block
hSquare = fill(XY(:,1),XY(:,2),'r','facealpha',0.5);
axis equal
end
axis([0 2 -1 1])

类别

Help CenterFile Exchange 中查找有关 Image Filtering and Enhancement 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by