Find number of words that will fit a frame

6 views
Skip to first unread message

M. S. Hrishikesh

unread,
May 17, 2012, 10:36:56 AM5/17/12
to cocoa-...@googlegroups.com
Hi

I have read the documentation of NSString methods that will return the size of the frame needed to fit the string. Example: 

sizeWithFont:forWidth:lineBreakMode:
sizeWithFont:constrainedToSize:lineBreakMode:
sizeWithFont:constrainedToSize:


What I need is - 

Given a frame size and a font size I want to know how many words will fit in that frame. 

Is there an easy way to do this?

Thanks


Ankur Acharya

unread,
May 17, 2012, 10:47:41 AM5/17/12
to cocoa-...@googlegroups.com
my guess is that you'd be able to figure out the number of characters, if at all, but not words, per se. 
eagerly waiting to read other comments!

Tom Butterworth

unread,
May 17, 2012, 10:51:30 AM5/17/12
to cocoa-...@googlegroups.com
Try the following...

1. Find the longest word in the user's language. You could build a lookup table for this. Remember plurals and past tenses can make a word even longer.
2. Assume a worst-case scenario where the user wishes to fill the frame only with repetitions of this word.
3. Divide the width of the frame by the width of this word for your desired font to give the number of words.
4. For German you can safely assume the number of words that will fit is one.

...

Hamish Allan

unread,
May 17, 2012, 10:51:46 AM5/17/12
to M. S. Hrishikesh, cocoa-...@googlegroups.com
On 17 May 2012 15:45, M. S. Hrishikesh <hri...@gmail.com> wrote:

> This is English text so spaces mark words. So what I really want it given a
> string of specific words, I am trying to figure out how many words will fit
> in a frame.

Do it iteratively: start at one word, keep doubling until you
overshoot, then bisect.

E.g. for the string "The quick brown fox jumps over the lazy dog".

Try fitting "The" into the frame -> fits
Try fitting "The quick" -> fits
Try fitting "The quick brown fox" -> fits
Try fitting "The quick brown fox jumps over the lazy" -> doesn't fit
Try fitting "The quick brown fox jumps over" -> fits
Try fitting "The quick brown fox jumps over the" -> gives you the answer.

H

Hamish Allan

unread,
May 17, 2012, 10:53:26 AM5/17/12
to M. S. Hrishikesh, cocoa-...@googlegroups.com
P.S. To optimise, start at N words rather than 1, where N is greater
than or equal to the number of lines that will fit on the page :)
Reply all
Reply to author
Forward
0 new messages