Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
For "unknown length" do you want a scroll bar? –  Vitaliy Kaurov Nov 26 '12 at 22:40
    
@VitaliyKaurov No, I just want it to grow in height (preferably downwards) –  ssch Nov 26 '12 at 22:42
    
@ssch I presume you tried playing with Pane[txt1,ImagesizeAction->"ResizeToFit"]? –  Gordon Coale 12 hours ago

1 Answer 1

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.