2008-09-27 61 views
7

我一直在尝试使用Quartz上下文显示文本,但无论我尝试过什么,我只是没有运气让文本显示(但我可以显示各种其他Quartz对象) 。任何人都知道我可能会做错什么?如何在iPhone上使用Quartz显示文本?

例如:

-(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); 
}  

回答

7

这里是代码的片段,我使用。

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

和:

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]; 
} 
+0

它应该是@“Sample Text”,因为函数需要一个NSString *。它适用于我,否则,谢谢。但是我找不到引用drawAtPoint函数,这是令人担忧的。 – CiscoIPPhone 2010-11-01 19:24:57

+1

drawAtPoint是UIKit NSString类别的一部分 - http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html – Hunter 2011-01-07 19:19:21

9

OK,我知道了。首先,将您的编码模式更改为kCGEncodingMacRoman。其次,在它下面插入此行:

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

这将设置文本的转换矩阵,以便正确绘制它。如果你没有放入这一行,你的文本将会颠倒并重新排列。不知道为什么这不是默认设置。最后,确保你已经设置了正确的填充颜色。如果您忘记从背景颜色更改为文本颜色,并以白底白字文本结束,则很容易犯错误。

相关问题