2

I'm trying to draw a UIlabel into a new Context, at a specific location. I know you can draw just the NSString into a context easily, but I want to retain the text size, color, and word wrap style of the UILabel. Thanks for your help!

 UIGraphicsBeginImageContext(targetSize);   

 // here is where I want to draw UILabel to context

 UIGraphicsEndImageContext();   
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
FierceMonkey
  • 1,964
  • 1
  • 16
  • 22

1 Answers1

3

You could draw any view using -renderInContext:, but if all you need is just retain the text size, color and word wrap style, you could simply use -drawInRect:withFont:lineBreakMode:alignment: to customize all options.

[label.textColor set];
[label.text drawInRect:label.bounds
              withFont:label.font
         lineBreakMode:label.lineBreakMode
             alignment:label.textAlignment];

There is also a -drawTextInRect: method in UILabel, but Apple says "You should not call this method directly."

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Awesome answer, I gave it a shot and it worked great, except that it is drawing at the top of the context ( top of the screen) as apposed to the bottom where the UILabel actually is. any thoughts? thanks again for your help! – FierceMonkey May 09 '11 at 02:51
  • @Fierce: Change `label.bounds` to any CGRect you like. – kennytm May 09 '11 at 06:52
  • I know this is a long time ago but I've been trying to find an answer like this for a long time. Do you know how to create this effect in Swift? I've been trying to translate it but can't figure it out. – martin Feb 15 '15 at 14:32
  • @frank21: `-drawInRect:withFont:...` has been deprecated, but you could use `drawInRect(_, withAttributes:_)` instead. – kennytm Feb 15 '15 at 18:22
  • Should I also add the linebreakmode and alignment as attributes? – martin Feb 15 '15 at 18:36
  • @frank21: If your UILabel doesn't use the default values, yes. Also you may need to add the shadowColor attributes as well. – kennytm Feb 20 '15 at 17:49