8
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ For "unknown length" do you want a scroll bar? $\endgroup$ Commented Nov 26, 2012 at 22:40
  • $\begingroup$ @VitaliyKaurov No, I just want it to grow in height (preferably downwards) $\endgroup$ Commented Nov 26, 2012 at 22:42
  • $\begingroup$ @ssch I presume you tried playing with Pane[txt1,ImagesizeAction->"ResizeToFit"]? $\endgroup$ Commented Oct 22, 2014 at 12:19

1 Answer 1

5
$\begingroup$

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

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.