用`text`绘图时如何包装字符串?

时间:2017-02-15 19:43:55

标签: matlab matlab-figure

我有一个长字符串,我想将其添加到子图中作为描述性文本。

description = 'This kitchen has white cabinets and two blue chairs. The upper cabinet has a black microwave. The paper towels are above the trash can. There is a black garbage can just on the left of the blue chair. On its left there is a red fire distinguisher.';

我试图在每个句子后面添加换行符,以使其更合适。

subplot(1,2,2);
with_new_lines = regexprep(description, '\.', '\.\n');
text( 0.5, 0.5, with_new_lines, 'FontSize', 14', 'FontWeight', 'Bold', ...
    'HorizontalAlignment', 'Center', 'VerticalAlignment', 'middle' ) ;

但它仍然不适合轴内。

有没有办法动态包装字符串以适应子图?

enter image description here

2 个答案:

答案 0 :(得分:3)

如果使用注释框,FitBoxToText属性关闭?

description = 'This kitchen has white cabinets and two blue chairs. The upper cabinet has a black microwave. The paper towels are above the trash can. There is a black garbage can just on the left of the blue chair. On its left there is a red fire distinguisher.';
figure;subH=subplot(1,2,2);
pos=get(subH,'Position');
annotation('textbox', pos,...
  'String', description,...
  'FitBoxToText','off');

您可以通过更改pos的前两个元素来更改位置,我认为这两个元素描述了左下角,但是忘了。

答案 1 :(得分:1)

您可以通过以下两种方式之一使用textwrap功能:

  1. 将文字换行以适合文字uicontrol

    hText = uicontrol('Style', 'Text', 'Position', ...(some starting position)... );
    [wrappedText, newPosition] = textwrap(hText, {description});
    set(hText, 'String', wrappedText, 'Position', newPosition);
    
  2. 在使用text绘图之前,将文本换行固定数量的列:

    wrappedText = textwrap({description}, 20);
    text(0.5, 0.5, wrappedText, 'FontSize', 14', 'FontWeight', 'Bold', ...
         'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');