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);
}
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];
}
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.
来源:https://stackoverflow.com/questions/143215/how-to-display-text-using-quartz-on-the-iphone