2011-03-14 21 views
0

我無法在自定義CALayer中繪製字符串。 drawInContext方法被調用,但屏幕上沒有任何東西可見。我可以用純色填充圖層,但似乎無法在其上繪製字符串。如何在OSX中的CALayer上繪製字符串?

有什麼建議嗎?謝謝。

- (void)drawInContext:(CGContextRef)ctx 
{ 
    CGContextSaveGState(ctx); 

    NSString *myString = @"Hello World";  
    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys: 
            [NSFont systemFontOfSize:14], NSFontAttributeName, nil]; 

    [myString drawAtPoint:NSMakePoint(0,0) withAttributes:attr]; 

    CGContextRestoreGState(ctx); 
} 

回答

2

我不想用Quartz畫一個字符串,但我想我必須這樣做。所以這是我最後做

NSString *string = @"Hello world"; 
    CGContextSelectFont (ctx,"Helvetica", 24, kCGEncodingMacRoman); 
    CGContextSetTextDrawingMode (ctx, kCGTextFillStroke); 
    CGContextShowTextAtPoint (ctx, 40, 40, [string UTF8String], (int)[string length]); 

替代解決方案

[NSGraphicsContext saveGraphicsState]; 

    NSGraphicsContext *currentContext = [NSGraphicsContext graphicsContextWithGraphicsPort:theContext flipped:NO]; 
    [NSGraphicsContext setCurrentContext:currentContext]; 

    //Draw here 

    [NSGraphicsContext restoreGraphicsState]; 
0

您可能想要使用CATextLayer。獲取父圖層,將文本添加到TextLayer,然後使用-addSublayer將TextLayer添加到父圖層。

+0

我有我需要繪製各種屬性的文本。我寧願自己繪製文本,因爲它比爲我的所有字符串創建CATextLayer並將其放入父圖層更通用。 – David 2011-03-15 02:32:43

相關問題