How can I get a string with a line break to be centered in a uicontrol?

조회 수: 21 (최근 30일)
I'm trying to center text with a line break in it in a figure, but the second line is never centered correctly. Here's an example:
f = figure('Position',[300,300,600,600]);
uicontrol('Parent',f,...
'Style','Text',...
'HorizontalAlignment','center',...
'Position',[20,300,560,280],...
'String',sprintf('This is a string that should be centered. It''s more apparent with longer lines.\nThis line definitely isn''t centered.'));
The second line is indented, but not centered. This is in R2020b if it matters. How can I get it to center correctly?
  댓글 수: 2
Rik
Rik 2020년 12월 2일
Sometimes assigning a cellstr works better. I don't remember if this is such a case.
Josh G.
Josh G. 2020년 12월 2일
Thanks, that fixed it. I passed the strings in in a cell array instead of through sprintf and now they're both centered correctly.

댓글을 달려면 로그인하십시오.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 12월 2일
I don't know why, but try and error and then got lucky.
%%
f = figure('Position',[300,300,600,600]);
uicontrol('Parent',f,...
'Style','Text',...
'HorizontalAlignment','center',...
'Position',[20,300,560,80],'backgroundcolor','r',...
'String',["This is a string that should be centered. It''s more apparent with longer lines.","Short line centered."]);
Comparing to
%%
f = figure('Position',[300,300,600,600]);
uicontrol('Parent',f,...
'Style','Text',...
'HorizontalAlignment','center',...
'Position',[20,300,560,80],'backgroundcolor','r',...
'String',['This is a string that should be centered. It''s more apparent with longer lines.',newline,'Short line not centered.']);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by