2011-11-18 31 views
9

假設我想一個字符串,說「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),以便填滿矩形。 你會如何使一個任意的字符串填充任意的矩形?

回答

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

+0

不錯的做法。順便說一句,如果你使用Scaled [1]而不是'{Scaled [1],Scaled [1]}',文本將垂直居中。 – DavidC

+0

@David謝謝。我試過了你的建議,但它不適用於我的系統。 : -/ –

+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}}]}] 
+0

哦,我喜歡將它拉伸以充分填充矩形的想法。但是,當我嘗試這個時,它看起來有顆粒感。我試着玩RasterSize參數無濟於事。我會繼續嘗試。謝謝佈雷特! – dreeves

+0

我不明白爲什麼它不起作用,如果你省略'ImageData'。另外,它似乎可以將Image更改爲Data。(然後省略ImageData)。 – Szabolcs

+0

@Szabolcs我沒有考慮使用''Data「'。出於某種原因,「Background - > None」不能正常工作,否則當其包含在紋理中時。 (當我第一次使用'Texture'創建類似的東西時,我不得不請求另一個開發人員。) –

1

建議的解決方案沒有工作時,情節不存在,我用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}}]];