Message Boards Message Boards

0
|
5599 Views
|
4 Replies
|
6 Total Likes
View groups...
Share
Share this post:

Set the size of an image based upon the rendered size of a string?

Posted 3 years ago

I am creating some labels for photographs. The labels will appear in the bottom left of each picture. I want the text to be rendered in a light grey rectangle, and I want the rectangle to be just large enough to contain the text.

Graphics[Style[Text["Label 1"], FontSize -> 16, FontColor -> Black]]

The above code produces the label correctly, but places it in a {360, 360} square, even though the text is only about 100px long, and about 30px high. I would like to create a graphic object that is proportional to the size of the text. Is there a way to do this?

POSTED BY: Andrew Burnett
4 Replies
Posted 3 years ago

@Ian, thanks for the additional info. I hadn't looked into Rasterize at all. It is clearly very powerful.

POSTED BY: Andrew Burnett
Posted 3 years ago

Brilliant! That's exactly what I need, and I have learned a new function.

Thanks very much for your help.

POSTED BY: Andrew Burnett
With[{text = Style[Text["Label 1"],
    FontSize -> 16, FontColor -> Black, Background -> LightGray]},
 Graphics[text, ImageSize -> ImageDimensions[Rasterize@text]]
 ]

This will fail in more places than it works, since ImageSize is not in pixels. Instead, use Rasterize[text, "BoundingBox"] and the result can be used in generating the ImageSize specification.

POSTED BY: Ian Hojnicki
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract