2008-09-27 65 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)); 

這將設置文本的轉換矩陣,以便正確繪製它。如果你沒有放入這一行,你的文本將會顛倒並重新排列。不知道爲什麼這不是默認設置。最後,確保你已經設置了正確的填充顏色。如果您忘記從背景顏色更改爲文本顏色,並以白底白字文本結束,則很容易犯錯誤。

相關問題