使文本字符串填充矩形

dre*_*ves 9 wolfram-mathematica image

假设我想要一个字符串,比如"123"来填充给定的矩形,如下所示:

Show[Plot[x, {x, 0, 1}], 
     Graphics[{EdgeForm[Thick], Yellow, Rectangle[{.1, .5}, {.4, .9}]}], 
     Graphics[Text[Style["123", Red, Bold, 67], {.1, .5}, {-1, -1}]]]
Run Code Online (Sandbox Code Playgroud)

矩形中的字符串

但我手动调整了那里的字体大小(67),以便它填满矩形.如何使任意字符串填充任意矩形?

Mr.*_*ard 8

我相信这是一个众所周知的难题.我能找到的最佳答案来自John Fultz.

TextRect[text_, {{left_, bottom_}, {right_, top_}}] := 
 Inset[
  Pane[text, {Scaled[1], Scaled[1]},
   ImageSizeAction -> "ResizeToFit", Alignment -> Center],
  {left, bottom}, {Left, Bottom}, {right - left, top - bottom}]

Show[
 Plot[x, {x, 0, 1}],
 Graphics[{
   {EdgeForm[Thick], Yellow, Rectangle[{.1, .5}, {.4, .9}]},
   TextRect[Style["123", Red, Bold], {{.1, .5}, {.4, .9}}]
 }]
]
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述