7

I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?

example:

-(void)drawRect:(CGRect)rect
{   
  // Drawing code
  CGContextRef  context = UIGraphicsGetCurrentContext();
  CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific);
  CGContextSetTextPosition(context,80,80);
  CGContextShowText(context, "hello", 6);
  //not even this works
  CGContextShowTextAtPoint(context, 1,1, "hello", 6);
}    
don
  • 1,497
  • 1
  • 13
  • 27
Robert Gould
  • 68,773
  • 61
  • 187
  • 272

2 Answers2

9

OK, I got it. First off, change your encoding mode to kCGEncodingMacRoman. Secondly, insert this line underneath it:

CGContextSetTextMatrix(canvas, CGAffineTransformMake(1, 0, 0, -1, 0, 0));

This sets the conversion matrix for text so that it is drawn correctly. If you don't put that line in, your text will be upside down and back to front. No idea why this wasn't the default. Finally, make sure you've set the right fill colour. It's an easy mistake to make if you forget to change from the backdrop colour to the text colour and end up with white-on-white text.

Duck
  • 34,902
  • 47
  • 248
  • 470
Ash
  • 9,064
  • 3
  • 48
  • 59
  • 1
    It's not the default because this function — and all of Quartz — operates exactly the same on iOS as on OS X for portability, but for some reason they inverted the [default] system-wide coordinate system on iOS. On the Mac (0, 0) is lower left, on iOS its top left. If you were porting Mac code, you'd invert and reposition the coordinate system just once before doing all of your code, rather than thinking about it for each primitive. – Tommy Aug 18 '11 at 22:10
7

Here is a fragment of code that I'm using.

UIColor *mainTextColor = [UIColor whiteColor];
[mainTextColor set];
drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16);

And:

static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,
                          int maxFontSize, int minFontSize) {
    CGPoint point = CGPointMake(left, y);
    UIFont *font = [UIFont systemFontOfSize:maxFontSize];
    [text drawAtPoint:point forWidth:right - left withFont:font
       minFontSize:minFontSize actualFontSize:NULL
       lineBreakMode:UILineBreakModeTailTruncation
       baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
}
Duck
  • 34,902
  • 47
  • 248
  • 470
Darron
  • 21,309
  • 5
  • 49
  • 53
  • It should be @"Sample Text" as the function expects a NSString*. It works for me otherwise, thanks. However I can't find reference to the drawAtPoint function, which is worrying. – CiscoIPPhone Nov 01 '10 at 19:24
  • 1
    drawAtPoint is part of the UIKit NSString category - http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html – Hunter Jan 07 '11 at 19:19