1

I have an NSString like @"Hello World" and want to convert that into an bitmap with exactly 20 pixels height. The width of the bitmap should match the width of the text.

I know there are some NSString UIKit additions that can draw text, but I don't know how to draw the text with an bounding box of exactly 20 pixels height (text fits perfectly into this height) into an bitmap that has the perfect size to carry the text?

Is there an easy way to do this?

This must also work with Chinese, Japanese, Russian and Arabic style letters. Maybe I could just put the text in a UILabel and then get it's content bitmap somehow. But the content bitmap of the UILabel would be either too short, or too long in width.

Maybe I must first ask the text itself how big it would be at a certain font size (= height?), and then manually create a bitmap with the exact dimensions needed, and draw the text on this bitmap?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
openfrog
  • 40,201
  • 65
  • 225
  • 373
  • SO, Off-topic, but: I wonder why people can favorite a question without voting it up?! If it's good, why not vote up automatically when favorited? Makes no sense. – openfrog Sep 23 '10 at 10:43
  • openfrog: Those are two unrelated actions. They probably would be coincident in 90% of cases, but one should never have one button do two separate things. (At least, not without a pref labeled “vote up any question that I favorite”.) – Peter Hosey Sep 23 '10 at 17:09
  • Then SO should ask automatically, if not voted up already: "Also vote up? YES / NO" ;) ... I just think it's egoistic to favorite a great question but then at the same time not supporting it by voting up. – openfrog Sep 25 '10 at 09:52

1 Answers1

3

The way I was told to do it for Cocoa at this question works, and despite the premature optimisation part of my brain doing a wobbly it isn't too slow.

Once you've drawn the text to your satisfaction, you can use this method to obtain an image representation of the view.

Community
  • 1
  • 1
  • Thanks Graham, that looks good. But it doesn't solve the problem of the exact bitmap. If I just draw it in a UIView's drawRect:, I must pre-guess the needed frame and then draw the text exactly in there, where the width doesn't matter. Only the height matters and must be at 20 pixels. – openfrog Sep 23 '10 at 09:12