使文本字符串填充矩形

时间:2011-11-18 05:42:07

标签: image wolfram-mathematica

假设我想要一个字符串,比如“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}]]]

a string in a rectangle

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

3 个答案:

答案 0 :(得分:8)

我认为这是一个众所周知的难题。我能找到的最佳答案is from 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}}]
 }]
]

enter image description here

答案 1 :(得分:2)

这是另一种将文本转换为映射到多边形的纹理的方法。这具有拉伸文本以适应该区域的特征(因为它不再是文本了。)

Show[Plot[x, {x, 0, 1}], 
   Graphics[{EdgeForm[Thick], Yellow, Rectangle[{.1, .5}, {.4, .9}]}], 
   Graphics[{Texture[ImageData[
      Rasterize[Style["123", Red, Bold], "Image", RasterSize -> 300, 
         Background -> None]]], 
      Polygon[{{0.1, 0.5}, {0.4, 0.5}, {0.4, 0.9}, {0.1, 0.9}}, 
         VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}]]

Mathematica graphics

作为便于比较的功能:

(* Render string/style s to fill a rectangle with left/bottom corner {l,b} and 
   right/top corner {r,t}. *)
textrect[s_, {{l_,b_},{r_,t_}}] := Graphics[{
  Texture[ImageData[Rasterize[s, "Image", RasterSize->300, Background->None]]], 
  Polygon[{{l,b}, {r,b}, {r,t}, {l,t}}, 
          VertexTextureCoordinates->{{0,0},{1,0},{1,1},{0,1}}]}]

答案 2 :(得分:1)

当Plot不存在时,建议的解决方案不起作用,我使用PlotRange选项来解决它。我把它包裹在一个函数中;不透明度,文字颜色等;应该做成选择;

textBox[text_, color_, position_: {0, 0}, width_: 2, height_: 1] := 
  Graphics[{
    {
     color, Opacity[.1],
     Rectangle[position, position + {width, height}, 
      RoundingRadius -> 0.1]
     }
    ,
    Inset[
     Pane[text, {Scaled[1], Scaled[1]}, 
      ImageSizeAction -> "ResizeToFit", Alignment -> Center], 
     position, {Left, Bottom}, {width, height}]
    }, PlotRange -> 
    Transpose[{position, position + {width, height}}]];