项目中遇到一个问题,需要把正三角形绕原点旋转任意角度,平时操作图片的时候,顺便旋转,感觉好像很简单,但是自己去做的时候还是有些困难。
我觉得旋转的难点在于由原始点计算新的目标点上,因为你需要考虑点位于四个象限以及坐标轴上的情况。我的做法是,先定正三角形的三个原始点和一个旋转的角度,
然后根据点所在的位置(判断点是在哪个象限或者坐标轴上),分别执行不同的新坐标计算代码,求出所有新的点坐标后,将点连接起来,就得到了新的三角形。
下面是我的代码,仅供参考:
主函数如下所示:
function [] = RotateFun()
%输入最大旋转角度,三角形按照步长为10度进行旋转
angle=input('please input the max rotate angle,angle=');
x0=[0,-1,1,0];
y0=[2/sqrt(3),-1/sqrt(3),-1/sqrt(3),2/sqrt(3)];%设定初始点的坐标
xmin=-2;
ymin=-2;
xmax=2;
ymax=2;
axis([xmin,xmax,ymin,ymax]);%设置图像的显示范围
plot(x0,y0,'-r'); %画出初始的三角形
hold on;
for angle_1=10:10:angle %根据设置的最大角度,每次增加10度画出新的三角形
theta=angle_1/180*pi;
[x(1),y(1)]= test_1(x0(1),y0(1),theta); %计算新点的坐标
[x(2),y(2)]= test_1(x0(2),y0(2),theta);
[x(3),y(3)]= test_1(x0(3),y0(3),theta);
x(4)=x(1);
y(4)=y(1);
axis([xmin,xmax,ymin,ymax]);
plot(x,y,'-b'); %画出新的图像
hold on;
end
end
调用的计算新点坐标的函数如下:
function [x,y] = test_1(x0,y0,angle)
%test_1 输入任一点和一个旋转角度,输出这一点绕坐标原点旋转angle角度的新坐标
if (x0>0)&&(y0>0) %point is at first phase
selects=1;
end
if (x0<0)&&(y0>0) %point is at second phase
selects=2;
end
if (x0<0)&&(y0<0) %point is at third phase
selects=3;
end
if (x0>0)&&(y0<0) %point is at fourth phase
selects=4;
end
if (x0>0)&&(y0==0) %point is at X+ axis
selects=5;
end
if (x0==0)&&(y0>0) %point is at Y+ axis
selects=6;
end
if (x0<0)&&(y0==0 ) %point is at X- axis
selects=7;
end
if (x0==0)&&(y0<0) %point is at Y- axis
selects=8;
end
switch selects
case 1 %计算位于第一象限的新点坐标
alfa=atan(y0/x0);
x=sqrt(x0^2+y0^2)*cos(pi/2+alfa+angle);
y=sqrt(x0^2+y0^2)*sin(pi/2+alfa+angle);
case 2 %计算位于第二象限的新点坐标
alfa=atan(abs(x0)/y0);
x=sqrt(x0^2+y0^2)*cos(pi/2+alfa+angle);
y=sqrt(x0^2+y0^2)*sin(pi/2+alfa+angle);
case 3 %计算位于第三象限的新点坐标
alfa=atan(abs(y0)/abs(x0));
x=sqrt(x0^2+y0^2)*cos(pi+alfa+angle);
y=sqrt(x0^2+y0^2)*sin(pi+alfa+angle);
case 4 %计算位于第四象限的新点坐标
alfa=atan(x0/abs(y0));
x=sqrt(x0^2+y0^2)*cos(3*pi/2+alfa+angle);
y=sqrt(x0^2+y0^2)*sin(3*pi/2+alfa+angle);
case 5 %计算位于x正半轴的新点坐标
x=sqrt(x0^2+y0^2)*cos(angle);
y=sqrt(x0^2+y0^2)*sin(angle);
case 6 %计算位于x负半轴的新点坐标
x=sqrt(x0^2+y0^2)*cos(pi/2+angle);
y=sqrt(x0^2+y0^2)*sin(pi/2+angle);
case 7 %计算位于y正半轴的新点坐标
x=sqrt(x0^2+y0^2)*cos(pi+angle);
y=sqrt(x0^2+y0^2)*sin(pi+angle);
case 8 %计算位于y负半轴的新点坐标
x=sqrt(x0^2+y0^2)*cos(3*pi/2+angle);
y=sqrt(x0^2+y0^2)*sin(3*pi/2+angle);
otherwise
end
end
运行结果如下: