Matlab任意两点之间绘制带箭头的直线

工作环境(蓝色粗体字为特别注意内容)

1,开发环境:Matlab 2012b win32

2,编程语言:Matlab

最近需要使用matlab绘制带箭头的直线,发现如下方式可以绘制带箭头的直线

1.调用annotation函数绘制二维箭头annotation函数用来在当前图形窗口建立注释对象(annotation对象),它的调用格式如下:
(1) annotation(annotation_type)  % 以指定的对象类型,使用默认属性值建立注释对象。
(2) annotation('line',x,y)       % 建立从(x(1), y(1))到(x(2), y(2))的线注释对象。
(3) annotation('arrow',x,y)      % 建立从(x(1), y(1))到(x(2), y(2))的箭头注释对象。
(4) annotation('doublearrow',x,y)% 建立从(x(1), y(1))到(x(2), y(2))的双箭头注释对象。
(5) annotation('textarrow',x,y)  % 建立从(x(1),y(1))到(x(2),y(2))的带文本框的箭头注释对象
(6) annotation('textbox',[x y w h])  % 建立文本框注释对象,左下角坐标(x,y),宽w,高h.
(7) annotation('ellipse',[x y w h])  % 建立椭圆形注释对象。
(8) annotation('rectangle',[x y w h])% 建立矩形注释对象。
(9) annotation(figure_handle,…)     % 在句柄值为figure_handle的图形窗口建立注释对象。
(10) annotation(…,'PropertyName',PropertyValue,…)  % 建立并设置注释对象的属性。
(11) anno_obj_handle = annotation(…)  % 返回注释对象的句柄值。

发现annotation绘制带箭头的直线还挺好用,但是唯一的不足就是需要坐标系在[0,1]范围内的标准坐标系,其他坐标系中绘制会报错!!!

于是自己写了一个函数来绘制带箭头的直线,函数如下:

%% 绘制带箭头的直线
function drawArrow(start_point, end_point,arrColor,lineColor,arrowSize,lineWidth)
% 从start_point到end_point画一箭头,arrColor箭头颜色,arrSize,箭头大小
%判断参数多少
switch nargin
    case 2
        arrColor  = 'r';
        lineColor = 'b';
        arrowSize = 2;
        lineWidth = 1;
    case 3
        lineColor = 'b';
        arrowSize = 2;
        lineWidth = 1;
    case 4
        arrowSize = 2;
        lineWidth = 1;
    case 5
        lineWidth = 1;
end
K                = 0.05;                    % 箭头比例系数
theta            = pi / 8;                  % 箭头角度
A1 = [cos(theta), -sin(theta);
    sin(theta), cos(theta)];                % 旋转矩阵
theta = -theta;
A2 = [cos(theta), -sin(theta);
    sin(theta), cos(theta)];                % 旋转矩阵

arrow           = start_point' - end_point';
%使得箭头跟直线长短无关(固定值)
arrow(arrow>=0) = arrowSize;
arrow(arrow<0)  = -arrowSize;

arrow_1         = A1 * arrow;
arrow_2         = A2 * arrow;
arrow_1         = K * arrow_1 + end_point'; % 箭头的边的x坐标
arrow_2         = K * arrow_2 + end_point'; % 箭头的变的y坐标

hold on;
grid on;
axis equal;
plot([start_point(1), end_point(1)], [start_point(2), end_point(2)],lineColor,'lineWidth',lineWidth);
% 三角箭头(填充)
triangle_x      = [arrow_1(1),end_point(1),arrow_2(1),arrow_1(1)];
triangle_y      = [arrow_1(2),end_point(2),arrow_2(2),arrow_1(2)];
fill(triangle_x,triangle_y,arrColor);
% 线段箭头(不填充)
% plot([arrow_1(1), end_point(1)], [arrow_1(2), end_point(2)],color,'lineWidth',arrowSize);
% plot([arrow_2(1), end_point(1)], [arrow_2(2), end_point(2)], color,'lineWidth',arrowSize);
hold off;
end

效果如下:

效果完美~~~~

猜你喜欢

转载自blog.csdn.net/pang9998/article/details/82697095
今日推荐