如題,多的就不說了,先上一個效果:
每隔0.1秒,綠色的直線轉動一個角度。
再看看代碼如何實現:
fuction main
clear;
clc;
%%%%%%%%%%%%%%%%%%%%%%%%%%主函數%%%%%%%%%%%%%%%%%%%%%%%%%%%
bTimeStep = 0.1; %%重繪時間間隔
bSaveAVI = 1; %%是否將重繪過程保存到視頻文件
initDegree = 0; %%初始位置,位於零度角
if bSaveAVI
aviname = input('input the file name for avi: ','s');
aviobj=avifile(aviname); %定義一個視頻文件用來存動畫
aviobj.quality=60;
aviobj.Fps=5;
end
r = 1; %%背景圖中圓的半徑
DrawBackGround(r); %%畫背景
hold on;
[xcoor,ycoor] = GetCorrByDegree(r, TransDegToRad(initDegree)); %%畫初始位置,零度角
x = [0 xcoor];
y = [0 ycoor];
h = plot(x,y,'g-');
degreeStepForTest = 20;%%用於測試用的角度增量
for sita = initDegree+degreeStepForTest:degreeStepForTest:360
[xcoor,ycoor] = GetCorrByDegree(r, TransDegToRad(sita)); %%獲取當前的角度對應的坐標
x = [0 xcoor];
y = [0 ycoor];
set(h,'XData',x,'YData',y); %%重置繪圖對象
drawnow; %%重繪
if bSaveAVI
frame=getframe(gca); %把圖像存入視頻文件中
im=frame2im(frame);
aviobj=addframe(aviobj,im);
end
pause(bTimeStep); %%暫停間隔
end
if bSaveAVI
aviobj=close(aviobj); %%關閉視頻文件句柄
end
%%%%%%%%%%%%%%%%%%%%%%%%%%子函數%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function radian = TransDegToRad(degree)
%%將角度轉換為弧度
radian = degree * pi / 180;
function [x y] = GetCorrByDegree(R, Degree)
%%根據角度和半徑計算當前點的坐標
x = R * cos(Degree);
y = R * sin(Degree);
function DrawBackGround(r)
%%%畫背景圖
x = linspace(-r,r,1000);
y1 = sqrt(r^2-x.^2);
plot(x,y1,'b-'); %%畫上半圓
hold on;
y2 = -sqrt(r^2-x.^2); %%畫下半圓
plot(x,y2,'b-');
axis square;
plot([0 0],[-r r],'b-'); %%畫縱直徑
plot([-r r],[0 0],'b-'); %%畫橫直徑
axis off;
hold off;
注釋寫的很詳細,不多說了。