7

Question: How to insert Styled text of unknown style and length into a graphics and have it wrap at a Scaled width?

Attempt: I found the following two ways to wrap text when I was googling:

(* Based on: http://forums.wolfram.com/mathgroup/archive/2008/Mar/msg00977.html *)
syd[txt_, w_: 100, h_: 50] := 
 Graphics[{Inset[Framed@txt, {0, 0}, {0, 0}, {w, h}]}]

(* Based on: http://forums.wolfram.com/mathgroup/archive/2008/Mar/msg00916.html *)
fred[txt_, w_: 150] := Graphics[{
   Inset[Framed@Pane[Style[txt, LineIndent -> 0, TextAlignment -> Left], w], {0, 0}]
   }]

But I want to handle text of unknown length so I did this to Syds solution:

(* Since {w,h}={100,50} worked for a string of length 460
it's reasonable to assume each character needs (100*50)/460 area units,
so any string should have area of StringLength[txt]*(100*50)/460 \
since w is given let 
h=StringLength[txt]*(100*50)/(460*w)
*)
sydGuessHeight[txt_, w_: 100] := 
 Graphics[{Inset[
    Framed@txt, {0, 0}, {0, 0}, {w, 
     StringLength[txt]*(100*50)/(460*w)}]}, 
  PlotLabel -> Style["syd guess: w=" <> ToString[w], Red, Bold]]

A test:

txt1 = (StringJoin @@ 
    Table["The quick brown fox jumped over the lazy dog. ", {10}]);
txt2 = (StringJoin @@ 
    Table["The quick brown fox jumped over the lazy dog. ", {20}]);
Grid[Partition[Image /@ {
    syd[txt1],
    syd[txt2],
    syd[txt2, 100, Automatic] ,
    fred[txt1],
    fred[txt2],
    sydGuessHeight[txt2]}, 2]]

enter image description here

This is all very inelegant and I still can't use it to wrap text of a Scaled width nor can I supply Styled text since any modification in font will break the guess.

ssch
  • 16,590
  • 2
  • 53
  • 88

1 Answers1

5

Instead of using Framed@txt you can use Framed@TextCell then you can resize and format ect.

sydGuessHeight2[txt_, w_: 100] := Graphics[{Inset[
    Framed@TextCell[
      Style[txt, LineIndent -> 0, TextAlignment -> Left], "Text", 
      CellMargins -> {{200, 200}, {10, 10}}], {0, 0}, {0, 0}, {w, 
     StringLength[txt]*(100*50)/(460*w)}]}, 
  PlotLabel -> Style["syd guess: w=" <> ToString[w], Red, Bold]]

txt2 = (StringJoin @@ 
    Table["The quick brown fox jumped over the lazy dog. ", {20}]);
sydGuessHeight2[txt2, 50]

The output

s.s.o
  • 4,559
  • 2
  • 27
  • 42