iPhone: how to draw text in a window?

grigoryvp picture grigoryvp · Jul 12, 2009 · Viewed 14k times · Source

Strange situation - examples from apple works, but after i change them a bit, text is not displayed. This bit of code correctly draws blue background but refuses to draw text on it no matter what i do:

#import <UIKit/UIKit.h>

@interface CWnd : UIWindow @end
@implementation CWnd

- (void) drawRect : (CGRect) i_poRect
{
  // This is working : windows is blue.
  CGContextRef oContex = UIGraphicsGetCurrentContext();
  CGContextSetRGBFillColor( oContex, 0, 0, 255, 1 );
  CGContextFillRect( oContex, i_poRect );
  // This is not working : not text is displayed.
  CGContextSelectFont( oContex, "Monaco", 10, kCGEncodingFontSpecific );
  CGContextSetRGBStrokeColor( oContex, 255, 0, 0, 1 ); 
  CGContextSetRGBFillColor( oContex, 255, 0, 0, 1 ); 
  CGContextSetTextDrawingMode( oContex, kCGTextFill );
  CGContextSetTextPosition( oContex, 100, 100 );
  CGContextShowText( oContex, "abc", 3 );
}

@end

@interface CDelegate : NSObject <UIApplicationDelegate> @end
@implementation CDelegate

- (void)applicationDidFinishLaunching : (UIApplication *) i_poApp
{
  CGRect oRect = [ [ UIScreen mainScreen ] bounds ];
    [ [ [ CWnd alloc] initWithFrame : oRect ] makeKeyAndVisible ];
}

@end

int main(int argc, char *argv[])
{    
  return UIApplicationMain( argc, argv, nil, @"CDelegate" );
}

Answer

Brad Larson picture Brad Larson · Jul 12, 2009

I've used the following code without problem to draw text directly to a Quartz context:

CGContextSetStrokeColorWithColor(context, strokeColor); 
CGContextSetFillColorWithColor(context, strokeColor);

CGContextSelectFont(context, "Helvetica", fontSize, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetTextPosition(context, 0.0f, round(fontSize / 4.0f));
CGContextShowText(context, [text UTF8String], strlen([text UTF8String]));

It's not obvious what's going wrong in your case. There are two things to watch out for in this case: the text may draw upside-down due to the flipped coordinate space of UIViews and their CALayers, and as Rhythmic Fistman points out, this doesn't handle UTF encodings.

A better, although less performant, approach is to do something like:

CGContextSetFillColorWithColor(context, strokeColor);
[text drawAtPoint:CGPointMake(0.0f, 0.0f) withFont:[UIFont fontWithName:@"Helvetica" size:fontSize]];