How do I add text to an image in Matlab and have that text wrap to fit within a specified textbox?

16 views (last 30 days)
I am trying to make a program that adds tet to an image, while also ensuring that the text does not go beyond the size of the image. I first tried using insertText, but I did not see a simple way to get the text to move down to the next line when it got to a certain length.
I really liked how the annotate function worked:
%Define Constants
blank = imread('blank.jpg');
txt = 'This is a test string.This is a test string.This is a test string.This is a test string.';
%Add Text
imshow(blank)
annotation('textbox', [.33,0.4,0.38,0.1],...
'String', txt,...
'FitBoxToText','off',...
'EdgeColor','none')
But unfortunatley annotate adds the text to a figure and I cant seem to find a simple way to get the image with the text out of that figure and when I save the figure as a png, I get a whole bunch of white space around it.

Answers (1)

Walter Roberson
Walter Roberson on 15 Jul 2021
Edited: Walter Roberson on 15 Jul 2021
The general approach is to create an interface object, ask to wrap the text inside the interface object, and extract the result.
https://www.mathworks.com/help/matlab/ref/textwrap.html can be used with traditional figures
In the first case, traditional figures, you might create a uicontrol() 'style', 'text' or 'style', 'edit', and configure it with the desired font and font size, and set the String property. Then textwrap() which gives you a cell array of character vectors. You then insert each of those into the image as a separate line.
Another useful fact is that once you set a uicontrol in the way I describe above, and cause it to render (even if you immediately make it invisible again), then after the control's Extent property will tell you what size you would need to render that particular text, taking into account proportional representation and the exact characters. That knowledge can help you figure out where in an image has room to place the text -- and can help pack text nicely instead of assuming that each section must have a fixed size.

Community Treasure Hunt

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

Start Hunting!